JSONP request to PHP page not working (cross domain)

感情迁移 提交于 2019-12-08 07:44:08

问题


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' i.e. its running the error function.

Using jQuery 1.5.2 any ideas?


回答1:


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.




回答2:


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
}

});



来源:https://stackoverflow.com/questions/5896965/jsonp-request-to-php-page-not-working-cross-domain

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!