Home > Backend Development > PHP Tutorial > How Does JSONP Solve Cross-Origin Request Issues?

How Does JSONP Solve Cross-Origin Request Issues?

Linda Hamilton
Release: 2024-12-12 15:15:18
Original
693 people have browsed it

How Does JSONP Solve Cross-Origin Request Issues?

Cross-Origin Requests with JSONP: A Practical Example

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.

Implementing JSONP for Cross-Origin Requests

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';
}
?>
Copy after login

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);
});
Copy after login

PHP:

<?php
$fname = $_GET['firstname'];
if ($fname == 'Jeff') {
  header("Content-Type: application/json");
  echo $_GET['callback'] . '({' . "'fullname' : 'Jeff Hansen'" . '})';
}
?>
Copy after login

Key Points:

  • ?callback=?: This parameter instructs the server to append the callback function name to the JSON response.
  • res.fullname: In JavaScript, we access the property value using dot notation. However, in this case, we need to prepend to treat the response as a JSON object.

Returning HTML in JSONP Responses

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>'
  })';
}
?>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template