可能重复:
从 $.ajax() 函数内部返回值
以下面的函数为例:
function($data) {
$.post(
url,
{
'data': $data
},
function(response){
return response;
}
);
}
我怎样才能使父函数:function($data) { ... }
return response
?
由于脚本的性质,我无法将其余的逻辑放入 post 回调中。(见下文)
var methods = {
'email' : function(field) {
var value = field.val();
var response = false;
field.addClass("loading");
$.post(
ajaxData.url,
{
'action':'validate_form',
'value': value,
'method': field.data('method')
},
function(response){
return response;
}
).complete(function() {
field.removeClass("loading");
});
},
'password' : function(field) {
var value = field.val();
var response = {};
if (value.length < 8) {
response.result = false;
response.message = 'Your password must be a minimum of 8 characters';
} else {
response.result = true;
response.message = false;
}
return response;
},
'verify_password' : function(field, dependancies) {
var value = field.val();
var response = {};
if (value != dependancies["password"].val()) {
if (!dependancies["password"].val() || !value) {
return false;
}
response.result = false;
response.message = 'Passwords do no match';
} else {
response.result = true;
response.message = false;
}
return response;
}
}
其中的每个属性methods
都是一个可以调用的函数,该return
值稍后在脚本中使用。
var response = methods[field.data('method')](field, field.data('dependancies'));