Home > Web Front-end > JS Tutorial > How Can JSONP Solve jQuery's Cross-Domain AJAX Problems?

How Can JSONP Solve jQuery's Cross-Domain AJAX Problems?

Mary-Kate Olsen
Release: 2024-12-30 09:32:14
Original
309 people have browsed it

How Can JSONP Solve jQuery's Cross-Domain AJAX Problems?

jQuery AJAX Cross-Domain Dilemma: Bypassing CORS with JSONP

Interacting with data across different domains poses challenges due to Cross-Origin Resource Sharing (CORS) restrictions. When attempting to perform an AJAX request from one domain to another, such as test.php on localhost and testserver.php on a remote server, browsers enforce these restrictions, leading to "Error" alerts.

To overcome this obstacle, JSONP (JSON with Padding) emerges as a viable workaround. It leverages the flexibility of script elements to retrieve data across domains.

jQuery Modifications:
Modify test.php to utilize JSONP by changing the dataType parameter to 'jsonp'.

PHP Modifications:
Adjust testserver.php to echo the JSONP response with the callback provided by jQuery.

Implementation:

jQuery (test.php):

$.ajax({
    url: "testserver.php",
    dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)
    success: function(json){
        // do stuff with json (in this case an array)
        alert("Success");
    },
    error: function(){
        alert("Error");
    }       
});
Copy after login

PHP (testserver.php):

<?php
$arr = array("element1", "element2", array("element31", "element32"));
$arr['name'] = "response";
echo $_GET['callback'] . "(" . json_encode($arr) . ");";
?>
Copy after login

Simplified Method Using $.getJSON():
Alternatively, use the $.getJSON() shorthand method, which automatically appends 'callback=?' to the URL as a GET parameter.

$.getJSON("testserver.php", function(json){
    // do stuff with json (in this case an array)
    alert("Success");
});
Copy after login

The above is the detailed content of How Can JSONP Solve jQuery's Cross-Domain AJAX Problems?. 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