Cross-Origin Request with JSONP: A Simple jQuery, PHP Example
When dealing with the limitations imposed by the same-origin policy, JSONP emerges as an effective solution for cross-origin requests. This technique allows you to retrieve data from external sources while avoiding the potential security vulnerabilities.
jQuery and JSONP
To initiate a JSONP request using jQuery, you can employ the $.getJSON method. This method automatically triggers a JSONP request, as demonstrated in the following code snippet:
$.getJSON('http://www.example.com/jsonp.php', {firstname: 'Jeff'}, function(res) { alert('Your name is ' + res.fullname); });
PHP and JSONP
On the server side, PHP serves as the endpoint for handling the JSONP request. The $.getJSON method appends a callback parameter to the URL query string, which is subsequently processed by the PHP script. The script returns the response wrapped in the callback function, as shown here:
<?php $fname = $_GET['firstname']; if ($fname == 'Jeff') { echo $_GET['callback'] . '(' . "{'fullname': 'Jeff Hansen'}" . ')'; } ?>
Note the use of $_GET['callback'] and the proper JSONP syntax in building the response. This ensures that the callback function provided by the client is used to encapsulate the response.
Handling HTML Results
While the example provided primarily illustrates the exchange of JSON data, it's worth noting that JSONP can also be used to transmit HTML content. To accommodate this, simply ensure that the PHP script wraps the HTML in the callback function and sends it as the response. The client-side JavaScript can then parse and render the HTML as needed.
The above is the detailed content of How Can jQuery and PHP Facilitate Cross-Origin Requests Using JSONP?. For more information, please follow other related articles on the PHP Chinese website!