Jakub Arnold
Jakub Arnold

Reputation: 87260

Unable to load JSONP data from external source using jQuery

I need to check if a stream is live on justin.tv. The provide a simple JSON API, where if I query

http://api.justin.tv/api/stream/list.json?channel=channel_name

it will return specific JSON info if the stream is live.

var url = "http://api.justin.tv/api/stream/list.json";

$.ajax({
  url: url,
  dataType: 'jsonp',
  data: { channel: "scvrush1" },
  success: function(data) { alert(data); }
});

It looks like the request is successful, because when I take a look at the Network tab in Chrome developer tools, I can see the response

jsonp request

but the callback doesn't get executed.

I'm using jQuery 1.4.2 packed with Rails 3.1.1, but I guess that's not relaly important.

Upvotes: 1

Views: 1311

Answers (2)

phihag
phihag

Reputation: 288260

As mentioned in the justin.tv REST API docs, the URL needs to specify the callback as ?jsonp=? (where the second question mark stands for the callback name that jQuery generates automatically). In jQuery, set the jsonp parameter:

var url = "http://api.justin.tv/api/stream/list.json";

$.ajax({
  url: url,
  dataType: 'jsonp',
  data: { channel: "scvrush1" },
  success: function(data) { alert(data); },
  jsonp: 'jsonp'
});

Here's a demo.

Upvotes: 0

Interrobang
Interrobang

Reputation: 17454

You must specify a callback function to use JSONP. The particular parameter that justin.tv asks for is "jsonp"

See: http://apiwiki.justin.tv/mediawiki/index.php/REST_API_Documentation

This is a little involved because they don't use the standard "callback=?" that jQuery likes. So you must manually set the callback variable.

See: http://api.jquery.com/jQuery.getJSON/#comment-75080188

This should work:

var url = "http://api.justin.tv/api/stream/list.json";

$.ajax({
  url: url,
  dataType: 'jsonp',
  data: { channel: "scvrush1" },
  success: function(data) { alert(data); },
  jsonp: "jsonp"
});

Upvotes: 2

Related Questions