29/06/2012

Access-Allow-Origin error when using jQuery getJSON

jQuery

I'm working on a test app that uses Twitter's search API to search against keywords. To make the call to Twitter's API I was using the getJSON function from jQuery. Like this:

 

$.getJSON(" http://search.twitter.com/search.json?q="+searchtrend,function(data){

    $(data.results).each(function(i,v)   {

    });

 

 

}

The problem I found was this was I was getting an Access-Allow-Origin error message. So searching around I found that the problem was a cross domain issue, similar to the issues you get in Flash when loading data from another domain. 

The solution to the problem I found was to use the $.ajax() function in jQuery, in this you can set the crossDomain to true. So my function now looks like this:

$.ajax({

 

url: "http://search.twitter.com/search.json?q="+searchtrend,

data: searchtrend,

type: 'GET',

crossDomain:true,

dataType:'jsonp',

success: callbackFunction,

error: function(){console.log('failed')}

});

 

 

Now this works without the Access-Allow error. Nice simple solution to a common problem.

No comments: