AJAX function to get JSON data
I made a script to get JSON data from a file on our server using AJAX but I'm having trouble putting it into a function.
Here's my code:
function getJSON (file)
{
var request = AjaxRequest();
var json = "";
request.onreadystatechange = function ()
{
if(request.readyState==4 && request.status==200)
{
json = JSON.parse(request.responseText);
}
}
request.open("GET", file, false);
request.send();
return json;
}
The function does everything I want it to but I've been told to NEVER pass false to the AJAX request because of blocking. Something just seems wrong about this function but I have no idea ho开发者_JS百科w to change it. Should I change it? If so, how?
You can't return it like this, it's an asynchronous operation, meaning your json = JSON.parse(request.responseText)
happens later, when the server responds with data...long after you returned.. Instead you can pass in a function which accepts the data, like this:
function getJSON (file, callback)
{
var request = AjaxRequest();
request.onreadystatechange = function ()
{
if(request.readyState==4 && request.status==200)
{
callback(JSON.parse(request.responseText));
}
}
request.open("GET", file, false);
request.send();
}
Then you call it like this:
getJSON("something.json", function(data) {
//use data, your json object/data
});
This way you're using the data when it's available, passing it onto the next function...this is the way asynchronous calls are intended to behave.
精彩评论