jQuery:将参数传递给ajax错误函数

时间:2012-06-19 13:44:42

标签: javascript jquery

这些天我一直在做一些ajax功能,我面临一个小问题。我有一个调用ajax的函数。我想给它一个值,并在请求完成时返回该函数。我该怎么做:

  • 触发ajax子功能的返回
  • 等待“answer”变更然后返回

这是精神(事实上,它无法奏效):

var answer = null;
    $.ajax({
        url: "validate/"+id,
        type: 'POST',
        data: {'field' : value},
        success: function(data) {
            //noty({text: data, type: 'success'});
        },
        error:function (xhr, ajaxOptions){
            noty({text: xhr.status + " : " + xhr.responseText, type: 'error'});
            answer = "error";
        } 
    });

return answer;

谢谢!

2 个答案:

答案 0 :(得分:4)

您不能从AJAX函数中return值,因为AJAX请求以异步方式发生(想想检索远程网页需要多长时间)。

相反,您需要提供一个回调(在请求完成时执行的函数):

function ajaxFunction(onComplete) {
    $.ajax({
        url: "validate/"+id,
        type: 'POST',
        data: {'field' : value},
        success: function(data) {
            //noty({text: data, type: 'success'});
            onComplete(data);
        },
        error:function (xhr, ajaxOptions){
            noty({text: xhr.status + " : " + xhr.responseText, type: 'error'});
            onComplete(error);
        }
    }
}

然后,您将一个函数作为参数传递给ajaxFunction,它将接收来自AJAX请求的响应。

ajaxFunction(function (answer) {
    // do something with answer
});

由于您需要idvalue参数,因此可以将其添加到ajaxFunction方法的参数中。

答案 1 :(得分:0)

使用async: false标志 - 请参阅jQuery.ajax文档以供参考。

请注意,在jQuery 1.8中,不推荐使用async

var answer = null;

$.ajax({
    url: "validate/"+id,
    type: 'POST',
    data: {'field' : value},
    success: function(data) {
        //noty({text: data, type: 'success'});
    },
    error:function (xhr, ajaxOptions){
        noty({text: xhr.status + " : " + xhr.responseText, type: 'error'});
        answer = "error";
    },
    async: false
});

return answer;