我正在尝试创建一个弹出模式,它将显示从php提交脚本回显的文本。到目前为止它的成功并打印出回显的内容,但我也希望在php脚本中发生异常时捕获回显的消息。
popnotify是一个单独的js函数,它接受文本输入并以文本作为段落显示模态。
createuser.php
try:
......
echo 'Successfully created a new user';
}
catch (PDOException $ex){
echo "Something went wrong when creating a new user";
http_response_code(403);
die();
}
的.js
jQuery("#load_form").on("click","#create_submit",function(event){
event.preventDefault();
var to_submit = $("#s_form").serialize();
var formLink = $("#s_form").attr('action');
jQuery('#load_form').find('input, select, button').prop('disabled', true);
$.post(formLink,to_submit)
.done(function(data){
popnotify_success(data);
})
.fail(function(data){
popnotify_fail(data);
})
.always(function(){
jQuery('#load_form').find('input, select, button').prop('disabled', false);
}); });
答案 0 :(得分:1)
如何使用标志来确定是否存在错误
您的PHP,createuser.php
try {
// Some more code here that tries to create the user
$response = [
'error' => 0,
'message' => 'Successfully created a new user',
];
echo json_encode($response);
}
catch (PDOException $ex){
$response = [
'error' => 1,
'message' => 'Something went wrong when creating a new user',
];
echo json_encode($response);
// HTTP Code 200 OK, there were not HTTP errors or server (500) errors
// http_response_code(403);
die();
}
您的JavaScript
jQuery("#load_form").on("click","#create_submit",function(event){
event.preventDefault();
var to_submit = $("#s_form").serialize();
var formLink = $("#s_form").attr('action');
jQuery('#load_form').find('input, select, button').prop('disabled', true);
$.post(formLink,to_submit)
.done(function(data){
// Parse the result into an object
var result = JSON.parse(data);
// Get the error flag from the object
if (result.error == 0) {
// There was no error
popnotify_success(result.message);
} else {
// There was an error
popnotify_fail(result.message);
}
})
.fail(function(data){
// Handle http errors here
})
.always(function(){
jQuery('#load_form').find('input, select, button').prop('disabled', false);
});
});
如果所有函数都创建通知,您也可以使用通用popnotify()
函数,而不是两个函数。依赖于错误/成功的任何其他代码都可以继承处理函数。