[英]Empty response on Error on ajax .post call
I'm doing an ajax call to delete an SQL entry. 我正在执行ajax调用以删除SQL条目。 If the entry is found and deleted, I return HTTP Code 200 with the message, that the entry was deleted. 如果找到并删除了该条目,则我将返回HTTP Code 200和该条目已被删除的消息。 So it jumps into the .done section and prints my message together with DONE . 因此它跳到.done部分,并与DONE一起打印我的消息。 In the case, the entry is not found, I want to jump into the .fail section, so I return HTTP Code 400 with my message, that the entry wasn't found. 在这种情况下,找不到该条目,我想跳到.fail部分,因此我返回HTTP Code 400和我的消息,即找不到该条目。 It prints the ERROR , but the message is always empty. 它显示ERROR ,但是消息始终为空。 If I check the return of the ajax call in the console of chrome I see my message together with code 400. 如果我在chrome控制台中检查ajax调用的返回,我会看到我的消息以及代码400。
$.post( 'ajax/project.php', data )
.fail(function(res) {
$( "#info" ).html("ERROR");
})
.done(function(res) {
$( "#info" ).html("DONE");
})
.always(function(res) {
$( "#debug" ).html(res);
});
Any solution to throw an error to jump into .fail but with receiving my error message? 有什么办法抛出错误跳入.fail但收到我的错误消息吗? I through the error like this: 我通过这样的错误:
function myError( $msg, $code=200, $die=true) {
http_response_code($code);
echo $msg;
if($die)
die();
}
My call of myError looks like this: 我对myError的调用如下所示:
if(!$stmt->affected_rows)
myError('Project #'.$pid.' not found', 400);
Edit2: As you can see in the screenshot below, with HTTP code 200 it just returns my message, in HTTP code 400 it returns my message in an object. Edit2:如下面的屏幕快照所示,使用HTTP代码200时,它仅返回我的消息,而使用HTTP代码400时,其在对象中返回我的消息。 Looks like I have to do a workaround to catch both possible returns, but I do not really understand why it acts different. 看来我必须采取一种变通方法来捕捉两种可能的回报,但是我并不真正理解为什么它的行为会有所不同。
Edit1: Just found out, if I alert the result with alert(res); Edit1:刚刚发现,如果我用alert(res)警报结果; in the .always section I get [object Object] in the error-case instead of my message. 在.always部分中,我在错误情况下获得了[object Object] ,而不是我的消息。
As you can see in this screenshot of the console of chrome, the server responses are different in case of success (200) and of error (400/500), but I don't know why.. 正如您在chrome控制台的屏幕截图中看到的那样,服务器响应在成功(200)和错误(400/500)的情况下是不同的,但是我不知道为什么。
However, this is a dirty hack, but it works for now. 但是,这是一个肮脏的骇客,但目前仍然有效。
$.post( 'ajax/project.php', data )
.fail(function(res) {
$( "#info" ).html("ERROR");
})
.done(function(res) {
$( "#info" ).html("DONE");
})
.always(function(res) {
console.log(res);
if(res instanceof Object)
$( "#debug" ).html(res.responseText);
else
$( "#debug" ).html(res);
});
If anybody can give me a better example of how to solve this, I would be happy :) 如果有人能给我一个更好的解决方法的例子,我会很高兴的:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.