0

我正在尝试在内部进行 jQuery AJAX 调用,$.when()以便在收到回调时执行其他操作。但不幸的是,我没有从我正在调用的方法中获得回调,该方法成功进行了 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);
    }
});

}
4

2 回答 2

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/

于 2013-02-06T23:11:36.810 回答
0

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

function makeAJAXRequest(pathString) {
    return $.ajax({
    // ...
    });
}
于 2013-02-06T23:22:52.580 回答