gpt4 book ai didi

javascript - 在循环中制作一个 jquery ajax POST

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:40:18 25 4
gpt4 key购买 nike

我在一个循环中有一堆数据,我想通过 jQuery 发布到服务器。

我的代码类似于以下内容:

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, textStatus, 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()

关于javascript - 在循环中制作一个 jquery ajax POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44400507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com