JSONP请求PHP页面不工作(跨域)

JSONP request to PHP page not working (cross domain)

本文关键字:工作 跨域 请求 PHP JSONP      更新时间:2023-09-26

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

<?php
header('Content-Type: application/json');
?>
stat({"online":1});
这是我的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有什么想法吗?

首先,JSON- p不是JSON。内容类型为application/javascript。有些浏览器可能会因为不安全而拒绝JSON- p作为JSON。

第二,getJSON期望你请求的URL有一个?作为回调方法名(你需要让你的PHP注意$_GET['callback'])。

第三,如果修复不工作,看看网络标签在Firebug/Chrome调试器/蜻蜓/等,看看什么数据实际上是通过电线。

包含一个"回调"函数有一些恶作剧。显然,您返回的不是对象,而是在原始客户机请求中提交的函数。我只是模糊地理解了这一切的含义,然而,我确实有一些代码来完成这个工作:

服务器端:

<?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).")";
?>

客户端(这与$.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
}

});