Ajax在成功回调上设置变量值

时间:2015-01-20 04:26:10

标签: javascript jquery ajax

我正在尝试向成功回调上的projectInfo变量添加/删除数据。这些价值似乎并不坚持。

function getIssues(projectInfo, callback) {
var projectData = projectInfo;

var promises = [];

for (keys = 0; keys < projectData.length; keys++) {

        var urlListData = // A url 
        var result = $.ajax({
            url: urlListData,
            type: "GET",
            async: true,
            beforeSend: function (xhr) {
                xhr.setRequestHeader("ACCEPT", accept);
            },
            success: function (xhr, textStatus) {
                if (xhr.d.results == "") {
                    console.log("I am removing this value" + xhr.d.results);
                    projectData.splice(keys, 1);
                    keys--;
                }
                else {
                    console.log("I add Issues");
                    console.log("The value of projectData is " + projectData[keys].Issues);
                    projectData[keys].Issues = xhr.d.results;
                    console.log("The value of projectData after setting is " + projectData[keys].Issues);
                }
            },
            error: function(xhr, ajaxOptions, thrownError){
                projectData.splice(keys, 1);
                keys--;
            }      
        })

        promises.push(result);
}

$.when.apply(null, promises).done(function () {
    console.log("Calling in the when promise");
    callback(projectData);
});

}

当我调用getIssues方法时,我会检查console.log值。日志值实际显示正在添加和删除问题,然后发生时间承诺。但是,getIssue方法返回的值不包含任何添加或删除的值。我做错了什么/错过了什么?

1 个答案:

答案 0 :(得分:0)

我简化了一点问题,这对我有用:

    function getIssues(urls, array, callback) {
        var promises = [];
        for (var key = 0; key < urls.length; key++) {

                var result = $.ajax({
                    url: urls[key],
                    type: "GET",
                    async: true,
                    success: function(xhr, textStatus) {
                        array.splice(-1)
                    }
                })

            promises.push(result);
        }

        $.when.apply(null, promises).done(function() {
            console.log("Calling in the when promise");
            callback(array);
        });
    }

    getIssues(["/firstUrl", "/secondUrl"], [1,2,3], function(array) {
        console.log('done', array); // array is [1] here ('spliced' twice)
    });

运行此操作(请记住关于更改/firstUrl/secondUrl),您可以隔离问题。