在jquery/ajax中使用错误功能 [英] Using error function in jquery/ajax

查看:124
本文介绍了在jquery/ajax中使用错误功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jquery在ajax/php中创建连接模块.我需要将异常从php抛出到ajax,以表明电子邮件或密码是否为假.

I'm working on a connection module in ajax/php using jquery. I need to throw an exception from php to ajax, to indicate whether email or password is false.

我在网上搜索了一种使用jquery的ajax提出的错误"功能的方法.找到了一些解决方案,但都不可行.

I searched all over the web for a way to use the 'error' function proposed by jquery's ajax. Found some solutions, none of them works.

尝试抛出php异常:错误函数未捕获到该异常;尝试通过发送json编码的数据来避免使用错误功能:无法在成功功能中使用它... 错误功能似乎只能捕获服务器错误,这确实没有意思.

Tried throwing a php exception : error function is not catching it ; tried avoiding using error function by sending json encoded data : no way of using it in success function... Error function seems to only catch server errors, which is really NOT interesting.

请问有人可以帮我找到一种通过Ajax交流php错误的方法吗?

Can anybody, please, help me find a way to communicate errors from php through ajax ?

推荐答案

设置请求状态代码在PHP响应4XX或5XX.这将使您最终进入error/fail回调.

Set the request statuscode in the php response to 4XX or 5XX. That will make you end up in the error/fail callback.

我不一定非要成为列表中的值.例如,您可以创建自己的:

I dones't necessarily have to be a value in the list. For example, you can create your own:

StatusCode: 550
StatusText: "My Custom Error"

如果我没记错的话,在PHP中看起来像这样:

Which, if I recall correctly, would look like this in PHP:

header('HTTP/1.0 550 My Custom Error');

最后,将错误详细信息发送给客户端,以通知他们发生了什么错误.您可以将信息放在标题中,也可以使用json_encode()

Finally, send the error details to the client to notify them of what went wrong. You can either place the info in the header, or serialize the exception using json_encode()

<?php

try {
    if (some_bad_condition) {
        throw new Exception('Test error', 123);
    }
    echo json_encode(array(
        'result' => 'vanilla!',
    ));
} catch (Exception $e) {
    echo json_encode(array(
        'error' => array(
            'msg' => $e->getMessage(),
            'code' => $e->getCode(),
        ),
    ));
}

?>

客户端:

$.ajax({
    url: 'page.php',
    data: { 'some_bad_condition': true }
}).done(function(data){

    console.log('success!', data);

}).fail(function(jqXhr){

    var errorObject = $.parseJSON(jqXhr.responseText);
    console.log('something went wrong:', errorObject);
    //jqXhr.status === 550
    //jqXhr.statusText === 'My Custom Error'

});

请不要忘记在您的PHP文件中指定正确的模仿类型.这样,jQuery无需明确指定即可知道它是JSON响应.

Don't forget to specify the correct mimetype in your PHP file. That way jQuery will know that it's a JSON response without you specifying it explicitly.

header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');

这篇关于在jquery/ajax中使用错误功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆