Raju Kumar
Raju Kumar

Reputation: 1265

Displaying jsonp data on web page

I'm trying to display data using jsonp but for some reason it doesn't wanna display on the web page.

function test() 
{
    $.ajax(
    {
        url: "http://localhost/api/company",  //web api is hosted on iss 8
        dataType: 'jsonp',
        success: function (data) 
        {
            $("#test").append(data[5].Company);
        }
    });
}

Please note the data return from the server is just fine. I tested this by executing the test function via google chrome and checking the response in network tab.

What could I be doing wrong here?

Upvotes: 1

Views: 1028

Answers (1)

Menelaos
Menelaos

Reputation: 26004

I would suggest you read a good explanation between JSON and JSON with Padding (JSONP) here in order to have a good understanding of what is going on: Can anyone explain what JSONP is, in layman terms?

First off the URL your calling needs to support JSONP. Not all webservices, rest interfaces, etc support it even if they produce JSON.

Secondly, you need to include a ?callback=? in your URL, in order to use JSONP from jquery.

You add ?callback=? to your URL, for example:

var url = 'URL?callback=?';
  $.getJSON(url, function(jsonp){
    $("#jsonp-response").html(JSON.stringify(jsonp, null, 2));
  });

You also need to test if the actual service supports JSONP, and you can do that opening in your browser your webservice with ?callback=something added

http://localhost/api/company?callback=callbackID

If the API supports jsonp you should see in your browser an output like:

callbackID({
    JSON DOCUMENT HERE
});

In the next section I'm including links to show what a standard JSON only response is, and what a JSONP response is.

Live Example Using Twitter API

When you use getJson to send the request and have ?callback=? jquery automatically adds a callback id.

The webserver gets a request such as and wraps the data up wth the callback name (this case "a"):

http://search.twitter.com/search.json?since_id=91770779645124609&q=test&callback=a

If you try the same request without the callback you see only JSON which cannot be consumed cross-site:

http://search.twitter.com/search.json?since_id=91770779645124609&q=test

Upvotes: 2

Related Questions