简体   繁体   中英

JSONP Callback function

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

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.

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 (eg if the response should always be JSON), you need to look into CORS as explained in this answer .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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