JSON.parse对象返回未定义的值

时间:2016-11-16 08:37:03

标签: javascript php jquery json

我有一个ajax请求,它从表单提交中返回一些非常基本的数据,如图所示。

PHP:

if ( ! empty($errors)) {

    // if there are items in our errors array, return those errors
    $data['success'] = false;
    $data['errors']  = $errors;
} else {

    $outputArray = array();

    $outputArray[] = array(
        'students' => base64_encode($_POST['students']),
        'sub' => $_POST['subject'],
        'topic' => $_POST['topic'],
        'class' => $_POST['class'],
        'checked' =>  $_POST['checked'],
        'pronoun' => $_POST['slider']
    );

    // if there are no errors process our form, then show a message of success and provide a true success variable
    $data['success'] = true;
    $data['message'] = json_encode($outputArray);
}

// return all our data to an AJAX call
echo json_encode($data);

使用Javascript:

$.ajax({
    type: 'POST',
    url: 'processBatch.php',
    data: formData,
    dataType: 'json',
    encode: true
})

.done(function(data) {
    if (!data.success) {
        // error handling goes here. Removed for clarity. 
    } else {
        // ALL GOOD!
        console.log(data.message);

        var obj1 = $.parseJSON(data.message);
        var obj2 = JSON.parse(data.message);

        console.log("Subject is: " + obj1.sub);
        console.log("Subject is: " + obj2.sub);
    }
}

从表面上看,一切似乎都很好 - 返回的数据似乎是有效的JSON(JSONlint将其清除为有效),但当我使用JSON.parse将其转换为对象时,并尝试引用该对象中的值,返回值始终未定义。我也试过$.parseJSON,结果是一样的。

一切看起来对我好,所以任何建议都会受到赞赏。

SAMPLE RETURNED STRING

[{
    "students": "TWlrZQpCb2IK",
    "sub": "English",
    "topic": "Test topic",
    "class": "Test classname",
    "checked": "WzEsNSw5XQ==",
    "pronoun": "2"
}]

2 个答案:

答案 0 :(得分:3)

您的JSON是一个数组。访问元素时使用数组索引。

console.log(data.message);
console.log("Subject is: " + data.message[0].sub);

另一种方法是重构从AJAX文件返回的数组,即将$outputArray[]更改为$outputArray。以下是示例

$outputArray = array();

$outputArray = array(
    'students' => base64_encode($_POST['students']),
    'sub' => $_POST['subject'],
    'topic' => $_POST['topic'],
    'class' => $_POST['class'],
    'checked' =>  $_POST['checked'],
    'pronoun' => $_POST['slider']
);

现在,在JS文件中,您可以直接访问元素而无需数组索引。

 console.log(data.message);
 console.log("Subject is: " + data.message.sub);

答案 1 :(得分:0)

如果你制作了JSON.stringify(数据)?