views:

2515

answers:

1

I need to make a synchronous request to the last.fm API, but when I use GET and json together, the request becomes asynchronous.

my code:

$.ajax({
      async: false,
    dataType: "json",
 url: "http://ws.audioscrobbler.com/2.0/?method=artist.getimages&artist="+artist+"&api_key="+apiKey+"&format=json&callback=?",
 success: function(html){
       imgURL = html.images.image[1].sizes.size[0]["#text"];
 }
});

If I remove dataType: "json" or use POST, it's synchronous again, but I'm dependant on using both json and GET.

Any ideas?

+5  A: 

Ah, this is because you're trying to do cross-domain requests, and cross-domain requests rely on a dynamic script tag, which can never be synchronous, must use datatype json and the GET method.

If you do a POST or remove the datatype, you will get an access error because of same-origin policy. It will return immediately, but as a failure.

altCognito
hmmm, guess I will have to find another way then... thanks for the reply anyway.
Could he bring the JSON string back as text and parse the JSON string to an object himself in his success() function using json2.js from www.json.org?
Lunchy
@Lunchy Not without something to handle redirecting the request on his side. The only way to get data in from another domain is to use the script tag and a callback function. It definitely appears that the service is geared towards exactly that by specifying the callback function as a URL. You can simulate blocking, but only using Javascript 1.7. http://hyperstruct.net/2008/5/17/synchronous-invocation-in-javascript-part-1-problem-and-basic-solution http://www.neilmix.com/2007/02/07/threading-in-javascript-17/
altCognito