Using JQuery $.get to determine return value?
I am trying to determine the return value of a function based on the result of a JQuery $.get request:
function checkResults(value) {
$.get("checkDuplicates.php", 开发者_开发技巧{
value: value
}, function(data) {
if(data == "0") {
//I want the "checkResults" function to return true if this is true
} else {
//I want the "checkResults" function to return false otherwise
}
});
}
Is there any easy way to do this?
You can't do it that way. .get()
like any other ajax method runs asynchronously (unless you explicitly set it to run synchronously, which is not very recommendable). So the best thing you can do probably is to pass in a callback.
function checkResults(value, callback) {
$.get("checkDuplicates.php", {
value: value
}, function(data) {
if(data == "0") {
if(typeof callback === 'function')
callback.apply(this, [data]);
} else {
//I want the "checkResults" function to return false otherwise
}
}
}
checkResults(55, function(data) {
// do something
});
No, you will need to supply a callback that will be executed once the request is complete. You can pass the return value to the callback. The callback will have to act on the result.
精彩评论