JSONP回调函数 [英] JSONP Callback function
问题描述
我一直在寻找到JSONP回调函数的概念。我阅读了有关的一些文章,希望抓紧做好JSONP的概念。
I was looking into the concept of JSONP callback function. I read some articles regarding that and wanted to get a good grasp of the concept of JSONP.
所以,我上传了1 JSON文件到服务器 - JSON文件
So, I uploaded one json file to the server - json file
这里是JS code,我写信给检索数据。该呼叫从本地主机向abhishekprakash.com。
And here is the js code which I wrote to retrieve the data. The call is made from localhost to the 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);
}
};
这是回应,我得到在控制台:
And this is the response that I get in the console:
回调函数的调用,但它不包含JSON数据。 我在想什么?
The callback function is called but it does not contain the Json data. What am I missing?
任何帮助是AP preciated。
Any help is appreciated.
感谢
推荐答案
这个例子服务返回JSON,而不是JSONP。
That example service returns JSON, not JSONP.
JSONP的一点是,由于同源策略的安全限制,Java脚本从域A不能做一个GET请求的资源域B上;换句话说脚本不能检索数据跨域
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通过使域B中的跨域数据共享明确合作解决这个问题。从域A脚本指定的回调函数的名称和嵌入域B的URL就好像它是包括常规外部JavaScript文件在文档中。域B然后输出的数据是这样的:
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, ... });
这意味着域B明确输出的 JavaScript片段的它要求的数据指定的回调函数。
That means domain B explicitly outputs a Javascript snippet which calls the specified callback function with the data.
所以,除非域B明确的合作,在此,你不能简单地从它那里得到一个JSONP响应。
So, unless domain B explicitly cooperates in this, you cannot simply get a JSONP response from it.
这篇关于JSONP回调函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!