[英]Jquery Post PHP always sending Success Response
I'm sending some data via Post to a php file, and I'm always retrieving a "success" in Jquery status even though the PHP is clearly sending back an error message. 我通过Post将一些数据发送到php文件,尽管PHP显然发回了错误消息,但我总是在Jquery状态下检索“成功”。
What's the reason behind that? 这是什么原因呢?
$.post('post.php',
{
post1:somevariable1,
post2:somevariable2,
post3:somevariable3
},
function(response,status){
if(status == "success") {
//success message (I'm always getting this)
}
else {
//error message
}
});
Post.php Post.php
if ($stmt === false) {
echo "error!!";
die(print_r(sqlsrv_errors(), true)); // This is what PHP is sending
} else {
echo "Success!!";
sqlsrv_free_stmt($stmt);
}
Thanks! 谢谢!
If you're sending the result of an operation as the return of a request, simply check the response in the success
callback` 如果您将操作结果作为请求的返回值发送,只需检查success
回调中的响应即可。
$.post('post.php',
{
post1:somevariable1,
post2:somevariable2,
post3:somevariable3
},
function(response,status){
if(response.status == "success") { // Here I'm checking the `response` argument
//success message (I'm always getting this)
}
else {
//error message
}
});
Where I've made the assumption that your response is being sent back from PHP as an object with the property status
: 我假设您的响应是从PHP作为具有属性status
的对象发送回的:
{
status: "success"|"error"
}
As has been pointed out in the other answers, your PHP file is completing and then returning a success status and so you always see status=='success'
. 正如其他答案中指出的那样,您的PHP文件正在完成,然后返回成功状态,因此您始终会看到status=='success'
。 What you actually want to do is check the value in response
. 您实际要做的是检查response
的值。 I would recommend doing something like: 我建议做这样的事情:
if ($stmt === false) {
echo json_encode(array('success' => false, 'reason' => sqlsrv_errors()));
exit;
} else {
echo json_encode(array('success' => true));
sqlsrv_free_stmt($stmt);
}
Then in your jquery do this: 然后在您的jquery中执行以下操作:
$.post('post.php',
{
post1:somevariable1,
post2:somevariable2,
post3:somevariable3
},
function(response,status){
let result = $.parseJSON(response);
if (result.success) {
echo "success!";
}
else {
echo "error: " + result.reason;
}
});
I think the problem is that there is not a problem going on, the server is giving you a response of 200, because it did'nt find an error. 我认为问题在于没有问题在继续,服务器给您200的响应,因为它没有发现错误。
try using headers inside the condition where you want it to fail like 尝试在您希望失败的条件下使用标题
header("HTTP/1.1 500 Internal Server Error");
exit;
//or try return false;
The post.php is responding with status 200 with a response. post.php的响应状态为200。 The browser/js doesn't check what text you are sending in the response. 浏览器/ js不会检查您在响应中发送的文本。
You can set the header to let the browser/just know about the error: 您可以设置标题以使浏览器/仅知道该错误:
header("HTTP/1.1 500 Internal Server Error");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.