Javascript 在循环中生成jquery ajax帖子
我想通过jQuery将一堆数据发布到服务器的循环中 我的代码类似于以下代码:Javascript 在循环中生成jquery ajax帖子,javascript,jquery,ajax,Javascript,Jquery,Ajax,我想通过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,
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);
}
});
var patients=[]//包含要发布到服务器的患者对象数组
var post=函数(URL、数据、回调){
$.ajax({
类型:“POST”,
url:theUrl,
数据:数据,
成功:回调,
contentType:“应用程序/json”
});
}
var createdPatient=功能(患者){
//病人是被创造出来的
}
$('#saveAll')。单击(函数(事件){
对于(变量i=0;i
当我运行代码时,只有最后一名患者已保存到服务器。如何纠正这个错误结果?利用jQuery.ajax()返回的承诺,您可以编写类似的内容(详细信息请参见注释):
有关更多详细信息,请参阅和使用调试器了解代码正在执行的操作。为什么不使用async?从jQuery 1.8开始,不推荐在jqXHR($.Deferred)中使用async:false@orbit我从点击F12得到的,打开你的开发者工具,寻找上面写着“网络”的标签。一旦您发现该请求,请执行导致请求发生的操作。在网络控制台中验证请求及其请求数据的#值是否准确。编辑:是的,避免异步:false。
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);
});
});