使用PHP json_encode了解JSON响应

时间:2011-08-16 16:24:27

标签: php jquery json

我有一个HTML表单,使用Jquery Form Plugin的.ajaxSubmit方法提交到PHP文件以进行MySQL插入。如果有错误,我无法从服务器获取错误响应,如果没有错误,则无法获得成功响应。我的代码工作正常,但我不明白为什么!

PHP提交文件的相关片段:

$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 {

然后创建MySQL记录和

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

.js中的成功函数是:

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]);
        }
    }
}

这就是我想要的,我理解第一部分。如果JSON对象经过错误检查,则只有'response'个密钥。 Firebug将此显示为服务器响应:

{"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."}

我不明白为什么语法'data[error]'或简单'data'用于回读错误。 Firebug中显示的响应是:

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

Firebug中显示的JSON是:

0        "The field cellPhone is required."

1        "The field homePhone is required."

它没有说明密钥中的错误,也没有定义新的“错误”对象。那么为什么Javascript允许定义''data [error]'`如果在响应中既没有对象也没有将键定义为错误?我猜`'data''是有效的,因为它只是回读返回对象中的每个值。

2 个答案:

答案 0 :(得分:1)

JSON对变量的内容进行编码,但不包含变量自己的名称。没有什么说你必须通过JSON传回一个字符串。您可以在单个变量中对整个消息系统进行编码。所以编码你想要的任何消息,一个子变量说“发生错误”,任何与该错误条件相关的错误消息等等......

$msgs = array();
if (...) {
    $msgs['message'] = 'blah blah blah';
}

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

echo json_encode($msgs);

然后,您可以让JS检查if (data.errors.length > 0)或类似的任何错误。

答案 1 :(得分:0)

for(var error in data)

这是一种遍历对象的方法,'错误'在这种情况下不是标签,你可能会在这里看到'错误'作为包含标签的变量(当前密钥,或者更好地称为成员名称)。您可以在这里使用任何您想要的“变量”-name。

for(var foo in data) {
        $("#frmPrntRgstr").prepend(data[foo]);
        }

......也会这样做。

这几乎与这个PHP代码类似:

foreach($data as $error => $message )
{
    echo $data[$error]
}

其中$ data是一个数组,并且在遍历数组时$ error是当前键。