Skip to content Skip to sidebar Skip to footer

External API GET() Request Using JQuery

I am using the IMDb API v2.0 located here and I decided to test it. I can't. I think it's beacuse of cross-browser AJAX request from external sites.. but I don't know any other way

Solution 1:

Replace:

$.ajax({
type: "GET",
url: "http://www.imdbapi.com/",
cache: false,
data: dataString,

success: function(html){
//$("#more").after(html);
alert("Success!");
}
});

With

$.getJSON('http://www.imdbapi.com/?' + dataString, function(json_data){
alert(JSON.stringify(json_data));
});

Solution 2:

It is a cross domain AJAX call, therefore you need a callback. jQuery makes this really easy, just add ?callback=? to your url.

url: "http://www.imdbapi.com/?" + dataString + "&callback=?"

Skip the data = dataString in this case, makes it easier (I find).

Try this, and continue on it further:

$.getJSON("http://www.imdbapi.com/?" + dataString + "&callback=?").success(function(data){
    console.log(data); // will contain all data (and display it in console)
})

This is the same as:

$.ajax({
type: "GET",
url: "http://www.imdbapi.com/?"+dataString+"&callback=?",
dataType: 'JSONP'
success: function(data){
    console.log(data);
}

Solution 3:

You can run cross domain Ajax with jQuery. Set the crossDomain option at the call site:

http://api.jquery.com/jQuery.ajax/

crossDomain(added 1.5)Boolean Default: false for same-domain requests, true for cross-domain requests If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true

Edit-

Actually, what exactly is your problem? I tried this and it returns Json properly.

http://jsfiddle.net/7VcUJ/

Response example:

HTTP/1.1 200 OK Cache-Control: no-cache Pragma: no-cache Content-Type: text/html; charset=utf-8 Expires: -1 Server: Microsoft-IIS/7.0 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Date: Mon, 02 Apr 2012 22:28:14 GMT Content-Length: 618

{"Title":"Avatar","Year":"2009","Rated":"PG-13","Released":"18 Dec 2009","Genre":"Action, Adventure, Fantasy, Sci-Fi","Director":"James Cameron","Writer":"James Cameron","Actors":"Sam Worthington, Zoe Saldana, Sigourney Weaver, Michelle Rodriguez","Plot":"A paraplegic marine dispatched to the moon Pandora on a unique mission becomes torn between following his orders and protecting the world he feels is his home.","Poster":"http://ia.media-imdb.com/images/M/MV5BMTYwOTEwNjAzMl5BMl5BanBnXkFtZTcwODc5MTUwMw@@._V1_SX320.jpg","Runtime":"2 hrs 42 mins","Rating":"8.1","Votes":"386930","ID":"tt0499549","Response":"True"}


Solution 4:

Add a callback parameter to the URL to use JSONP:

dataString = "t=Avatar&callback=?";

Using a $ will cause jQuery to auto-generate a callback function for you and handle the response automatically.

Recommended reading: What is JSONP all about?


Post a Comment for "External API GET() Request Using JQuery"