When encountering cross-origin policy restrictions, JSONP (JSON with Padding) offers a convenient solution. However, the specifics can be confusing to grasp initially. Let's demystify the process with a straightforward jQuery, PHP, and JSONP example.
Consider the following incorrect code snippet:
// jQuery $.post('http://MySite.com/MyHandler.php', { firstname: 'Jeff' }, function(res) { alert('Your name is ' + res); }); // PHP <?php $fname = $_POST['firstname']; if ($fname == 'Jeff') { echo 'Jeff Hansen'; } ?>
To enable cross-origin requests, we'll leverage JSONP. Here's how:
jQuery:
$.getJSON('http://www.write-about-property.com/jsonp.php?callback=?', { firstname: 'Jeff' }, function(res) { alert('Your name is ' + res.fullname); });
PHP:
<?php $fname = $_GET['firstname']; if ($fname == 'Jeff') { header("Content-Type: application/json"); echo $_GET['callback'] . '({' . "'fullname' : 'Jeff Hansen'" . '})'; } ?>
Key Points:
Yes, you can store HTML in JSONP responses. Modify the PHP code as follows:
<?php if ($fname == 'Jeff') { header("Content-Type: application/json"); echo $_GET['callback'] . '({ 'name': 'Jeff Hansen', 'html': '<span>This is some HTML</span>' })'; } ?>
In JavaScript, you can then access the HTML using res.html.
The above is the detailed content of How Does JSONP Solve Cross-Origin Request Issues?. For more information, please follow other related articles on the PHP Chinese website!