对 PHP 页面的 JSONP 请求不起作用(跨域)
这是我的 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');
});
});
出于某种原因,它总是记录“否”,即它正在运行错误函数。
使用 jQuery 1.5.2 有什么想法吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,JSON-P 不是 JSON。内容类型应为
application/javascript
。某些浏览器可能会因为不安全而拒绝将 JSON-P 用作 JSON。其次,getJSON 期望您请求的 URL 有一个
?
作为回调方法名称(并且您需要让您的 PHP 注意$_GET['callback']< /代码>)。
第三,如果修复不起作用,请查看 Firebug / Chrome 调试器 / Dragonfly / 等中的“网络”选项卡,看看实际通过网络传输的数据是什么。
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.
有一些恶作剧包含“回调”功能。显然您没有返回一个对象,而是返回一个在原始客户端请求中提交的函数。我只是模糊地理解这一切意味着什么,但是,我确实有一些实际有效的代码来做到这一点:
服务器端:
客户端(这与 $.getJSON() 是一样的):
});
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:
Client side ( this is the same thing as $.getJSON() ):
});