私は、フォームの送信からかなり基本的なデータを返すajaxリクエストを示しています。未定義の値を返すJSON.parseオブジェクト
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返された文字列
[{
"students": "TWlrZQpCb2IK",
"sub": "English",
"topic": "Test topic",
"class": "Test classname",
"checked": "WzEsNSw5XQ==",
"pronoun": "2"
}]
はあなたがcosole.logで見つけたもの全体 –
として返さ 'data'オブジェクト(data.message)のサンプルを与えてもらえますか?質問全体をオブジェクトで編集することを意味します。 – Bhavin
'data'をロギングしてみてください。 '.sub 'には問題があるようです。 – Rajesh