Abhishek Prakash
Abhishek Prakash

Reputation: 964

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:

snap shot of console

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

Any help is appreciated.

Thanks

Upvotes: 3

Views: 34543

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173542

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.

Upvotes: 7

deceze
deceze

Reputation: 522016

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.

Upvotes: 16

Related Questions