简体   繁体   English

对 PHP 页面的 JSONP 请求不起作用(跨域)

[英]JSONP request to PHP page not working (cross domain)

This is my PHP page (on a different URL)...这是我的 PHP 页面(在不同的 URL 上)...

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

And this is my jQuery:这是我的 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.由于某种原因,它总是记录“否”,即它运行错误 function。

Using jQuery 1.5.2 any ideas?使用 jQuery 1.5.2 有什么想法吗?

First, JSON-P is not JSON.首先,JSON-P 不是 JSON。 The content type should be application/javascript .内容类型应该是application/javascript Some browsers may reject JSON-P served as JSON for being unsafe.某些浏览器可能会因为不安全而拒绝用作 JSON 的 JSON-P。

Second, getJSON expects that the URL you request to have a ?其次,getJSON 期望您请求的 URL 具有? for the callback method name (and you'll need to get your PHP to pay attention to $_GET['callback'] ).对于回调方法名称(你需要让你的 PHP 注意$_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.第三,如果修复不起作用,请查看 Firebug / Chrome 调试器 / Dragonfly / 等中的 Net 选项卡,查看实际传输的数据。

There's some shenanigans with having with include a "callback" function.有一些恶作剧包括“回调”function。 Apparently you're not returning an object, but a function that was submitted in the original client request.显然,您返回的不是 object,而是原始客户端请求中提交的 function。 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() ):客户端(这与 $.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
}

}); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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