Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
43
rated 0 times [  49] [ 6]  / answers: 1 / hits: 32546  / 11 Years ago, fri, april 19, 2013, 12:00:00

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:



snap



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



Any help is appreciated.



Thanks


More From » ajax

 Answers
34

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.


[#78785] Thursday, April 18, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zoey

Total Points: 120
Total Questions: 103
Total Answers: 105

Location: Marshall Islands
Member since Mon, May 31, 2021
3 Years ago
;