您好,我无法弄清楚我在哪里出错了,因为删除功能运行良好,但是即使 JSON 响应返回成功,错误也会被触发。
$(document).on('click', '.remove-btn', function() {
var id = $(this).data('id');
var confirmDelete = confirm("Are you sure you want to remove this User");
formData = {
'form_process' : 'Remove User',
'id' : id,
}
if (confirmDelete) {
$.ajax({
type : 'POST',
url : 'library/page/process/remove_user.php',
data : formData,
dataType: 'json',
beforeSend: function(){
window.scrollTo(0, 0);
$("#loading-overlay").show();
},
success : function(data) {
$("#loading-overlay").hide();
if (!data.success) {
danger ('Process Error', data.errors)
} else {
success ('Success', 'User has been removed successfully.');
setTimeout(function() {
window.location.href = window.parent.CloseDialog();
}, 3000);
}
},
error : function (xhr, ajaxOptions, thrownError) {
$("#loading-overlay").hide();
danger ('Process Error', "There is unknown error occurs. Please contact administrator for system verification")
console.log(xhr.status);
console.log(xhr.responseText);
console.log(thrownError);
console.log('There is unknown error occurs. Please contact administrator for system verification');
}
});
}
})
下面是remove_user.php代码
if($_POST['form_process'] == 'Remove User') {
$training_info = $c_eta->_get_user_info($_POST['id']);
if (count($training_info) > 0) {
if ($c_eta->_remove_user($_POST['id'])) {
$form_data['success'] = true;
} else {
$form_data['success'] = false;
$form_data['errors'] = "Unable to remove user";
}
echo json_encode($form_data);
return;
}
}
json 响应是
{"success":true}
用户已被删除,但我不断收到的消息是
"Process Error', "There is unknown error occurs. Please contact administrator for system verification"
。
我尝试按照此处其中一篇文章的建议在
header('Content-Type: application/json');
之前添加 echo json_encode($form_data);
,但它不起作用。
您应该发送带有所有必要标头的响应,尤其是响应代码。
if($_POST['form_process'] == 'Remove User') {
$training_info = $c_eta->_get_user_info($_POST['id']);
if (count($training_info) > 0) {
if ($c_eta->_remove_user($_POST['id'])) {
$form_data['success'] = true;
} else {
$form_data['success'] = false;
$form_data['errors'] = "Unable to remove user";
}
header("HTTP/1.1 200 OK");
header("Content-Type: application/json");
// Optionally you may decide to add CORS support
header('Access-Control-Allow-Origin: *');
echo json_encode($form_data);
return;
}
}