jquery plugin functions return values
I stripped all my logic out of my jquery plugin for this question, but my problem is that when I call my function checkValidationName, it does it's thing and sets name = to true. Then when i try to compare it right after where i called it, the value is false. Why is this?
(function($){
$.fn.validate = function() {
var name = false;
$('.submitBtn').click(function() {
$.fn.validate.checkValidationName(nameValues);
**console.log("name = "+name); **//but this prin开发者_Python百科ts out "false"****
//shouldn't this be true since name returned true in the actual function??
}
});
$.fn.validate.checkValidationName = function(id) {
$.post("PHP/submitButtonName.php", {checkValidation: id},
function(data) {
**console.log("name = "+name); **//this prints out "true"****
//name is equal to true here
}, "json");
};
}
})(jQuery);
That's because the AJAX requests are asynchronous and right after you called checkValidationName
, it hasn't finished yet. You need to do the comparison in the callback.
You can make checkValidationName
take a callback and call it with the result when validated:
(function($){
$('.submitBtn').click(function() {
$.fn.validate.checkValidationName(nameValues, function(valid) {
console.log(valid);
});
});
$.fn.validate.checkValidationName = function(id, callback) {
$.post("PHP/submitButtonName.php", {checkValidation: id},
function(data) {
var valid = data.foo; // or however you determine that
callback(valid); // call callback
}, "json");
};
}(jQuery));
It's because the call to $.post() in checkValidationName
is asynchronous. When you invoke the following line...
$.fn.validate.checkValidationName(nameValues);
Execution continues to the next line almost right away -- long before you get a result fro $.post(), at any rate.
精彩评论