简体   繁体   中英

JSONP request to PHP page not working (cross domain)

This is my PHP page (on a different URL)...

<?php
header('Content-Type: application/json');
?>
stat({"online":1});

And this is my jQuery:

$(document).ready(function(){

    var url = 'http://blah.com/jsontest.php?callback=stat';

    $.getJSON(url, function(data) {
        if (data.online !== undefined) {
            console.log('yay');
        }
    }).error(function() {
        console.log('no');
    });

});

For some reason it is always logging 'no' ie its running the error function.

Using jQuery 1.5.2 any ideas?

First, JSON-P is not JSON. The content type should be application/javascript . Some browsers may reject JSON-P served as JSON for being unsafe.

Second, getJSON expects that the URL you request to have a ? for the callback method name (and you'll need to get your PHP to pay attention to $_GET['callback'] ).

Third, if fixing that doesn't work, look at the Net tab in Firebug / Chrome debugger / Dragonfly / etc and see what data is actually going across the wire.

There's some shenanigans with having with include a "callback" function. Apparently you're not returning an object, but a function that was submitted in the original client request. I only vaguely understand what all that means, however, I do have some code to do this that actually works:

Server Side:

<?php
$headers = get_headers($toGetUrl,1);
$return["pop_singer"] = "Britney Spears";
// Right here is where the json object gets wrapped in a function that was submitted under the name "callback"
echo $_GET['callback']."(".json_encode($return).")";
?>

Client side ( this is the same thing as $.getJSON() ):

$.ajax({
type: "GET",
url: serverUrl,
dataType: 'jsonp',
error: function(request, status) {
    // Do some error stuff
},
success: function(data, textStatus, jqXHR) {
    var property = data.pop_singer;   // equals "Britney Spears"
    // Do some successful stuff
}

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM