最初加载页面时,ajax会填充一个selectmenu。当我输入新的患者信息时,它会被添加到数据库中,但患者选择菜单不会被选中的新患者附加/刷新。
我希望有人可以帮我解决我做错的事。
Ajax调用
$('#newpatient').click(function() {
var patientadd = $('#patientaddform').serializeArray();
$.ajax({
url: 'patientadd.php',
type: "POST",
data: patientadd,
dataType: 'json',
success: function(data) {
var html = '';
var len = data.length;
for (var i = 0; i < len; i++) {
html += '<option value="' + data[i].patient_id + '">' + data[i].patient_firstname + ' ' + data[i].patient_lastname + '</option>';
}
$('#patientselect').append(html);
},
complete: function() {
$('#patientselect').selectmenu('refresh', true);
}
});
});
patientadd.php
if (empty($_POST) === false) {
$update_data = array('company_id' = > $_POST['company_id'], 'addpatient_firstname' = > $_POST['addpatient_firstname'], 'addpatient_lastname' = > $_POST['addpatient_lastname'], 'addpatient_dob' = > $_POST['addpatient_dob'], 'patient_added' = > $_POST['patient_added']);
$required_fields = array('company_id', 'addpatient_firstname', 'addpatient_lastname', 'addpatient_dob', 'patient_added');
foreach($update_data as $key = > $value) {
if (empty($value) && in_array($key, $required_fields) === true) {
$errors[] = 'Fields marked with an asterisk are required';
break 1;
}
}
}
if (empty($_POST) === false && empty($errors) === true) {
$company_id = $_POST['company_id'];
$patient_id = $_POST['addpatient_id'];
$first_name = $_POST['addpatient_firstname'];
$last_name = $_POST['addpatient_lastname'];
$dob = $_POST['addpatient_dob'];
$updated = $_POST['patient_added'];
$update = array();
array_walk($update_data, 'array_sanitize');
foreach($update_data as $field = > $data) {
$update[] = '`'.$field.'` = \''.$data.'\'';
}
mysql_query("INSERT INTO `lab`.`patients` (`company_id`, `patient_id`, `patient_firstname`, `patient_lastname`, `patient_dob`, `patient_added`) VALUES ('$company_id', NULL, '$first_name', '$last_name', '$dob', '$updated')");
$patient_id = mysql_insert_id(); /*echo '<strong>' . $patient_id . ' ' . $first_name . ' ' . $last_name . '</strong> has been added!';*/
}
$data = array('patient_id' = > $patient_id, 'patient_firstname' = > $first_name, 'patient_lastname' = > $last_name);
echo json_encode($data);
答案 0 :(得分:1)
将代码从complete
移至success
函数。
$('#newpatient').click(function() {
var patientadd = $('#patientaddform').serializeArray();
$.ajax({
url: 'patientadd.php',
type: "POST",
data: patientadd,
dataType: 'json',
success: function(data) {
var html = '';
var len = data.length;
for (var i = 0; i < len; i++) {
html += '<option value="' + data[i].patient_id + '">' + data[i].patient_firstname + ' ' + data[i].patient_lastname + '</option>';
}
$('#patientselect').append(html);
$('#patientselect').selectmenu('refresh', true);
},
complete: function() {
//$('#patientselect').selectmenu('refresh', true);
}
});
});
Ajax执行是异步的。 success
方法仅执行请求返回的方法。但是,success
被触发,complete
也被触发。这意味着您最终处于竞争状态,complete
在success
执行完毕之前执行。 Complete
不等待success
完成。 <{1}}和success
几乎同时执行。
确保您的刷新调用包含complete
后success
内的新数据执行刷新。