dongmiyi8220 2011-08-16 16:24
浏览 44
已采纳

使用PHP json_encode了解JSON响应

I have an HTML form that submits to a PHP file for MySQL insertion using the Jquery Form Plugin's .ajaxSubmit method. I was having trouble getting error responses from the server if there were errors, and a success response if there were no errors. I've got the code working, but I don't understand why!

Pertinent snippet of the PHP submission file:

$reqs = array('userName', 'Pwd', 'firstName', 'lastName', 'email', 'cellPhone', 'homePhone', 'role');
foreach($reqs as $req) {
    if((!isset($_POST[$req])) || (empty($_POST[$req]))) {
            $newerr = "The field " . $req . " is required.";
            $errors[] = $newerr;
    }
}
if(!empty($errors)) {
echo json_encode($errors, JSON_FORCE_OBJECT);
} else {

then create the MySQL record and

$success = array('response'=>"Request successfully submitted. Your account must be configured before you can access the user panel. Please watch for an email confirming your registration and configuration.");
        echo json_encode($success);

The success function in the .js is:

function processJson(data) {
    if(data.response) {
        $("#frmPrntRgstr").slideUp("normal", function() {
            $("#frmPrntRgstrRspns").append(data.response).slideDown("normal");
        })
    } else {
        for(var error in data) {
        $("#frmPrntRgstr").prepend(data[error]);
        }
    }
}

This does what I want it to, and I understand the first part. There is only a 'response' key in the JSON object if it's gotten past error checking. Firebug shows this as the server Response:

{"response":"Request successfully submitted. Your account must be configured before you can access the user panel. Please watch for an email confirming your registration and configuration."}

I don't understand why the syntax 'data[error]' or simply 'data' works for reading back the errors. The response shown in Firebug is:

{"0":"The field cellPhone is required.","1":"The field homePhone is required."}

The JSON shown in Firebug is:

0        "The field cellPhone is required."

1        "The field homePhone is required."

It doesn't say error in the key, and it doesn't define a new "Errors" object. So why does that Javascript allow the definition `'data[error]'` if there's neither an object nor a key defined as error in the response? I guess `'data'` works because it's just reading back each value in the returned object.

  • 写回答

2条回答 默认 最新

  • dsxay48646 2011-08-16 16:35
    关注

    JSON encodes the contents of a variable, but does not include the variable's own name. Nothing says that you have to pass back only a single string via JSON. You can encode an entire message system in a single variable. So encode any messages you want, a sub-variable to say "error occured", any error message(s) associated with that error condition, etc...

    $msgs = array();
    if (...) {
        $msgs['message'] = 'blah blah blah';
    }
    
    if (...) {
        $msgs['errors'][] = 'error message here';
    }
    
    echo json_encode($msgs);
    

    Then you can have your JS check for any errors with if (data.errors.length > 0) or similar.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP