jQuery通过父函数返回$.post回调
jQuery return $.post callback through parent function
可能重复:
$.ajax()函数内部的返回值
以以下函数为例:
function($data) {
$.post(
url,
{
'data': $data
},
function(response){
return response;
}
);
}
如何使父函数function($data) { ... }
返回response
?
由于脚本的性质,我无法将我的其余逻辑放入后回调中(见下文)
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'));
AsAJAX
的A代表Asynchronous
,所以您不能随心所欲地返回。您可以尝试使用如下回调函数:
function($data, callback) {
$.post(
url,
{
'data': $data
},
function(response){
return callback(response);
}
);
}
例如:
var myObj = {
myfunc: function($data, callback) {
$.post(
url,
{
'data': $data
},
function(response){
return callback(response);
}
);
}
}
myObj.myfunc($data, function(response) {
// process here with response
});
相关文章:
- jQuery$.post可以在chrome、safari中工作,但不能在FF中工作(声明成功回调函数未定义)
- jQuery post,访问responseType或回调中的响应
- jQuery load()回调导致POST而不是GET
- 从类方法中的 ajax post 函数回调函数更改 javascript 类属性
- $.post到PHP文件-在包含循环完成之前不会调用回调
- $.post.done回调未启动,但数据已发布到服务器
- jQuery通过父函数返回$.post回调
- 无法在 $.post 回调中设置作用域变量
- POST 响应未等待回调完成
- 使用 $.post 将基本 JSON 发送到 php,并带有回调
- 茉莉花 - 间谍属性进入 jquery.post 回调
- JQuery ajax post 回调函数未执行
- 在 jQuery post 上接收带有 HTML 的回调
- $.post 和 $.ajax 回调未与 Bootstrap 一起运行
- Jquery post回调不起作用
- 为什么我的Jquery .post回调函数不能工作?
- Javascript -从$.post回调后,实例类的属性未定义
- 如何在$.post()回调显示alert()之前调用函数
- Javascript中post回调的问题
- jQuery:如何在Post回调数据中查找当前对象