在jQuery中使用$ .when获取延迟调用

时间:2013-02-06 23:02:41

标签: jquery

我正在尝试在$.when()内进行jQuery AJAX调用,以便在收到回调时执行其他操作。但不幸的是,我没有从我调用的方法获得回调,这使得成功的AJAX调用。以下是代码......

/****** Code which calls the function ******/

var pathString = "/Cities?state=" + whichState;

$.when(makeAJAXRequest(pathString)).done(function(data)
{
    alert(data);                  //Shows undefined

    //Other operations ..... 
}

/****** My function which makes the AJAX call ******/

function makeAJAXRequest(pathString)
{

$.ajax({
        type:'GET',
        async:'false',
        cache:false,
        url:'./proxy.php',
        data:{path:pathString},         //Can put the query-string in the path. But if put in data attribute, it will work with both GET and POST
        dataType:'xml',
        success:function(data)
        {
    //alert(data);

    return data;
    },
    error:function(xhr, textStatus, errorThrown)
    {
    alert("Error in AJAX request: " + textStatus + errorThrown);

    return ("Error in AJAX request: " + textStatus + errorThrown);
    }
});

}

2 个答案:

答案 0 :(得分:0)

问题是你真的没有在makeAjaxRequest()方法中返回一个延迟对象。

它应该是这样的:

function makeAJAXRequest(pathString) {
    var deferred = new $.Deferred();
    $.ajax({
        type:'GET',
        async:'false',
        cache:false,
        url:'./proxy.php',
        data:{path:pathString}
        dataType:'xml',
        success:function(data) {
            // Deferred object success
            return deferred.resolve(data);
        },  
        error:function(xhr, textStatus, errorThrown) {
            alert("Error in AJAX request: " + textStatus + errorThrown);
            // Deferred object reject
            return deferred.reject("Error in AJAX request: " + textStatus + errorThrown);
        });
    return deferred.promise();
    }

请仔细查看延期文档:http://api.jquery.com/category/deferred-object/

答案 1 :(得分:0)

makeAJAXRequest()中,您只需要返回$.ajax jqXHR对象http://api.jquery.com/jQuery.ajax/#jqXHR

function makeAJAXRequest(pathString) { return $.ajax({ // ... }); }
{{1}}