Ajax函数(带嵌套)
function open_appointment(id)
{
save_method = 'open_appointment';
$('#form_open_appointment')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('ReceptionistController/ajax_edit_appointment')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$.ajax({
url : "<?php echo site_url('DoctorController/ajax_edit_patient')?>/" +data.ap_patient,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="pt_name"]').val(data.pt_name);
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Failed');
}
});
$('#modal_open_appointment').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Open Appointment'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
我想在另一个中使用一个ajax调用。我已经编写了上面的代码,但它不起作用(嵌套时),并给出show&#34; Failed&#34; 。嵌入ajax调用函数存在问题
答案 0 :(得分:3)
你可以使用下面的承诺
代码未经测试......
供参考: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
var getAppointment = function() {
return new Promise(function(resolve, reject) {
$.ajax({
url : "<?php echo site_url('ReceptionistController/ajax_edit_appointment')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
resolve(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
reject('Error get data from ajax');
}
});
})
}
var editPatient = function(data) {
return new Promise(function(resolve, reject) {
$.ajax({
url : "<?php echo site_url('DoctorController/ajax_edit_patient')?>/" +data.ap_patient,
type: "GET",
dataType: "JSON",
success: function(data)
{
resolve(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
reject('Failed');
}
});
}
}
getAppointment()
.then(function(data) {
return editPatient(data)
})
.then(function(data) {
$('[name="pt_name"]').val(data.pt_name);
})
.catch(function(error) {
console.log(error)
));
答案 1 :(得分:0)
语法看起来很好,但首先,检查外部ajax请求它是否正常工作并正确返回data.ap_patient。之后调用内部ajax请求。并检查请求是否要更正操作方法的检查元素。