JSONP Callback function

只愿长相守 提交于 2019-12-17 16:50:58

问题


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.

So, I uploaded one json file to the server - json file

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:

The callback function is called but it does not contain the Json data. What am I missing?

Any help is appreciated.

Thanks


回答1:


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.




回答2:


The XHR is constrained by cross-domain rules; to use JSONP you need to add a script element:

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);

As pointed out by Ian in the comments, the proper response of your server should be something like this:

func_callbk('hello world')

Update

If you wish to make this work without JSONP (e.g. if the response should always be JSON), you need to look into CORS as explained in this answer.



来源:https://stackoverflow.com/questions/16097763/jsonp-callback-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!