微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

javascript – 在循环中创建一个jquery ajax POST

我在循环中有一堆数据我想通过jQuery POST到服务器.

我的代码类似于以下内容

var patients = [] // contains an array of patient objects I want to POST to server

var post = function(theUrl,theData,callback){
    $.ajax({
        type: "POST",url: theUrl,data: theData,success: callback,contentType: "application/json"
    });
}

var createdPatient = function(patient){
    //patient was created
}

$('#saveAll').click(function(event) {
    for (var i = 0;i < patients.length;i++) {
        var json = JSON.stringify(patients[i]);
        post("/openmrs/ws/rest/v1/patient",json,createdPatient);
    }
});

当我运行代码时,只有最后一位患者已保存到服务器.我该如何纠正这种错误的结果呢?

解决方法

利用jQuery.ajax()返回的promise,你可以编写更像这样的东西(详见评论):

var patients = [...] // contains an array of patient objects to be POSTed to the server

$('#saveAll').click(function(event) {
    // first,map the `patients` array to an array of jqXHR promises as returned by $.ajax().
    var promises = patients.map(function(patient) {
        return $.ajax({
            type: 'POST',url: '/openmrs/ws/rest/v1/patient',data: patient,// jQuery.jax will handle js plain objects here. You may need to stringify here if patient is not a plain object.
            contentType: "application/json"
        }).then(function(data,textStatus,jqXHR) {
            return textStatus; // report successes in the form of the "textStatus" message (or anything you like).
        },function(jqXHR,errorThrown) {
            return $.when(textStatus || errorThrown); // report error on the success path,otherwise `$.when()` will bail out at the first error.
        });
    });
    // Now aggregate the `promises` array with `$.when()`
    $.when.apply(null,promises).then(function(results) {
        console.log(results);
    },function(error) {
        // due to error handling above,you should never get here.
        console.log(error);
    });
});

有关更多详细信息,请参阅jQuery.ajax()jQuery.when()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐