Wrap a jquery function and return a value
You can I wrap this code so that when a call a function returns the variable contianing the json object?
Example:
function GetNewSomething() {
var newtb = 0;
$.get("/something/new",
开发者_开发百科 function (data) {
newtb = data;
}
);
return newtb; // as of now this always returns undefined...
}
Tried this way, but only return undefined..
Thanks in advance guys!
regards,
You can't. Ajax calls are asynchronous. You have to pass a callback to your function:
function GetNewSomething(cb) {
$.get("/something/new", cb);
}
and call it with:
GetNewSomething(function(data) {
// do something with data
});
I wrote something about it.
Oh and if the response is a JSON string, you might want to use .getJSON
which also decodes the response into a JavaScript object.
.get()
is a wrapper to $.ajax()
. All AJAX request run asyncronously if not explicitly configured otherwise. That in turn means, that your return newtb;
statement will occur before $.get()
has finished.
A good way to workaround this issue is to invoke another callback on your own. This could look like:
function GetNewSomething(callback) {
$.get("/something/new",
function (data) {
if( typeof callback === 'function' )
callback.apply(this, [data]);
}
);
}
And then call it like
GetNewSomething(function(data) {
// do something with data
});
The $.get
is asyncronous, which is the reason you pass it a function to call when the get request returns.
You could change to make the $.get
a $.ajax
and make it syncronous since $.get
is just a wrapper for a $.ajax
:
function GetNewSomething() {
var newtb = 0;
$.ajax({url:"/something/new",
type:"GET",
async:false,
success: function (data) {
newtb = data;
}
});
return newtb;
}
精彩评论