PHP返回false,但$.post接收true


PHP returns false but $.post receives as true

我在互联网上搜索,但实际上我没有成功,所以我在这里尝试:)

我有一个jquery函数,比如:

var arr = [];
$.post('my.php',{
      data:  arr
     }).done(function(response){
        console.log(response);
       alert('successful');
     }).fail(function(response){
       console.log(response);
       alert('failure');
});

我的php看起来像

$bOk = false; //preset
//...
return $bOk; // actually returns false here for testing

这些是代码示例,但实际上它就是这样做的。

为什么return false不调用.fail()

如果我有php错误,它会调用.fail()

调用.fail()函数需要做些什么吗

.fail()用于HTTP错误。如果你要做类似header("HTTP/1.0 404 Not Found");的事情,它应该触发FAIL。但目前,它返回200 OK message,因为它从服务器获得响应。

尝试实现404响应,或者在.success()调用中,检查响应是否包含错误响应。

编辑。

需要注意的是,我举的例子(404)的回答可能不是最合适的(这取决于您的申请情况)。

请在此处查看此链接以获取HTTP状态代码列表,并决定什么是最有效的。最有可能的是,看看400和500的范围。

http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

fail回调应该用作fail回调,所以只有当某些东西真的失败时。

在您的情况下,您可能会返回错误代码,因此在成功回调时,您将执行以下操作:

var arr = [];
$.post('my.php',{
    data:       arr
}).done(function(response){
    if(response==2){
     alert('password is invalid');
     return;
    }
    console.log(response);
    alert('successful');
}).fail(function(response){
    alert('An unexpected error occurs, please contact the administrator if this error persist.');
});

如果您仍然想在失败回调中进行登录,那么在这种情况下,是的,您需要使用http_response_code php函数返回http状态,如下所示:

http_response_code(404);

false不返回http错误

如果您想在.fail()中返回reach的http错误,请使用以下代码

if ($everything_is_ok)
    {
        header('Content-Type: application/json');
        print json_encode($result);
    }
else
    {
        header('HTTP/1.1 500 Internal Server Booboo');
        header('Content-Type: application/json; charset=UTF-8');
        die(json_encode(array('message' => 'ERROR', 'code' => 1337)));
    }