Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

php - Using error function in jquery/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.

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.

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"

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

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

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(),
        ),
    ));
}

?>

Client side:

$.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'

});

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');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...