我在循环中有一堆数据我想通过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);
}
});
当我运行代码时,只有最后一位患者已保存到服务器。我该如何纠正这种错误的结果?
答案 0 :(得分:0)
利用jQuery.ajax()
返回的承诺,你可以写更多这样的东西(详见评论):
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()