简体   繁体   English

发送ajax响应的最佳实践是什么?

[英]What is best practice in sending ajax response?

I have a webapp that calls php thus: 我有一个Web应用程序,因此会调用php:

    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? 并且我想知道什么是php脚本中公认的最佳实践?

For example, if all works well, my php returns: 例如,如果一切正常,我的php返回:

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: 如果出现意外错误,例如SQL错误,我的php将返回:

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

prior to calling die(). 在调用die()之前。 I then handle this in .fail(). 然后,我在.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()? 是否可以使用“内部服务器错误”,还是应该使用某种json响应协议来通知JavaScript错误,并在.done()中查找此错误?

Any advice much appreciated. 任何建议,不胜感激。

Thanks 谢谢

Mini 微型

I think you should check the header response from server-side script and use switch case accordingly. 我认为您应该检查服务器端脚本的标头响应,并相应地使用switch大小写。 For eg:- if the header response is json then use different case, if header response is failed ajax call then use different case. 例如:-如果标头响应为json,则使用不同的大小写;如果标头响应为失败的ajax调用,则使用不同的大小写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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