dqzpt40064
dqzpt40064
2011-05-05 11:30
浏览 122

JSONP请求PHP页面无法正常工作(跨域)

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?

图片转代码服务由CSDN问答提供 功能建议

这是我的PHP页面(在不同的URL上)......

 &lt;?php 
header('Content-Type:application / json'); 
?&gt; 
stat({“online”:1}); 
   \  n 
 

这是我的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'); 
}); 
 
}); 
   
  
 

由于某种原因,它始终记录'no',即它运行错误函数。

使用jQuery 1.5.2任何想法?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongqiang2069
    dongqiang2069 2011-05-05 11:38
    已采纳

    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.

    点赞 评论
  • drl9940
    drl9940 2011-07-27 23:44

    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
    }
    

    });

    点赞 评论

相关推荐