3

我正在研究 JSONP 回调函数的概念。我阅读了一些关于此的文章,并希望很好地掌握 JSONP 的概念。

于是,我上传了一个json文件到服务器——json文件

这是我为检索数据而编写的 js 代码。呼叫是从 localhost 向 abhishekprakash.com 发出的。

var xhr;
var dataList;
xhr = new XMLHttpRequest();

xhr.open('GET', 'http://abhishekprakash.com/script/example.json?callback=func_callbk',  true);
xhr.send();

func_callback = function(data){
    alert(data.data.people[0].id);
}

xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
            console.log(dataList);
    }
};

这是我在控制台中得到的响应:

控制台快照

回调函数被调用,但它不包含 Json 数据。我错过了什么?

任何帮助表示赞赏。

谢谢

4

2 回答 2

15

That example service returns JSON, not JSONP.

The point of JSONP is that due to Same Origin Policy security restrictions, Javascript from domain A cannot make a GET request to resources on domain B; in other words a script cannot retrieve data cross-domain.

JSONP solves this by making domain B explicitly cooperate in the cross-domain data sharing. The script from domain A specifies the name of a callback function and embeds the URL of domain B in the document as if it were including a regular external Javascript file. Domain B then outputs data like this:

callbackFuncName({ data : foo, ... });

That means domain B explicitly outputs a Javascript snippet which calls the specified callback function with the data.

So, unless domain B explicitly cooperates in this, you cannot simply get a JSONP response from it.

于 2013-04-19T05:34:33.720 回答
7

XHR 受跨域规则约束;要使用 JSONP,您需要添加一个脚本元素:

function func_callbk()
{
    console.log(arguments);
}

var s = document.createElement('script');
s.type = 'text/javascript';
s.src = 'http://abhishekprakash.com/script/example.json?callback=func_callbk';
var h = document.getElementsByTagName('script')[0];
h.parentNode.insertBefore(s, h);

正如 Ian 在评论中指出的那样,您的服务器的正确响应应该是这样的:

func_callbk('hello world')

更新

如果您希望在没有 JSONP 的情况下进行这项工作(例如,如果响应应始终为 JSON),则需要按照此答案中的说明查看 CORS 。

于 2013-04-19T05:31:28.063 回答