[英]JSON.parse object returning undefined values
我有一個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
,結果是一樣的。
一切看起來都還好我,所以任何建議,將不勝感激。
樣本返回字符串
[{
"students": "TWlrZQpCb2IK",
"sub": "English",
"topic": "Test topic",
"class": "Test classname",
"checked": "WzEsNSw5XQ==",
"pronoun": "2"
}]
您的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);
如果您制作JSON.stringify(data)?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.