JSONP: Cross-Origin Data Retrieval Simplified
When dealing with cross-origin web requests, the same-origin policy can pose a challenge. JSONP (JSON with Padding) emerged as a solution to address this issue. Here's a step-by-step explanation of how to implement a basic jQuery, PHP, and JSONP request to retrieve data from a different domain:
jQuery Request
$.getJSON('http://www.write-about-property.com/jsonp.php?callback=?', { firstname: 'Jeff' }, function(res) { alert('Your name is ' + res.fullname); });
PHP Response
<?php $fname = $_GET['firstname']; if ($fname == 'Jeff') { echo $_GET['callback'] . '(' . "{'fullname' : 'Jeff Hansen'}" . ')'; } ?>
Key Modifications:
HTML in Response
Yes, you can store HTML in the result and it will be returned as a string. The JavaScript code will then handle the HTML as appropriate.
Example Usage
This example retrieves the full name of 'Jeff' from a PHP script located at 'http://www.write-about-property.com/jsonp.php'. If the name matches 'Jeff', the full name 'Jeff Hansen' is returned.
The above is the detailed content of How Does JSONP Solve Cross-Origin Data Retrieval Problems?. For more information, please follow other related articles on the PHP Chinese website!