简体   繁体   中英

What is best practice in sending ajax response?

I have a webapp that calls php thus:

    var jqxhr = 
        $.getJSON( url )
        .done( function( data, status ) {
            if( status == 'success' ) {
                rv = true;
                // initialise the user object
                app.user = new User( data );

                // post login-processing
                app.postLogin();
            } else {
                // login failed
                console.log( "autologin failed!" );
            }
        })
        .fail( function() {
            console.log( "autologin fail" );
    }); // end var jqxhr =

and I'm wondering what is accepted as best practice in the php script?

For example, if all works well, my php returns:

header('Content-type: application/json; charset=utf-8');
print json_encode($row);

If there's an unexpected error, such as bad SQL, my php returns:

header('HTTP/1.1 500 Internal Server Error');
header('Content-Type: application/json; charset=UTF-8');
etc.

prior to calling die(). I then handle this in .fail().

But what if I want to return an EXPECTED error, such as 'Invalid username or password'? Is it ok to use 'Internal Server Error', or should I be using some kind of json response protocol to inform the javascript of the error, and looking for this in .done()?

Any advice much appreciated.

Thanks

Mini

I think you should check the header response from server-side script and use switch case accordingly. For eg:- if the header response is json then use different case, if header response is failed ajax call then use different case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM