2016-11-16 9 views
0

私は、フォームの送信からかなり基本的なデータを返す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" 
}] 
+1

はあなたがcosole.logで見つけたもの全体 –

+0

として返さ 'data'オブジェクト(data.message)のサンプルを与えてもらえますか?質問全体をオブジェクトで編集することを意味します。 – Bhavin

+0

'data'をロギングしてみてください。 '.sub 'には問題があるようです。 – Rajesh

答えて

2

JSONは配列です。要素にアクセスする際に配列インデックスを使用します。

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

別のアプローチは、アレイ、すなわち$outputArray$outputArray[]を変更AJAXファイルから返された再構築することです。以下はその例です

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

私は助けることができてうれしいです。ハッピーコーディング:) – Samir

0

あなたはJSON.stringify(データ)を作成した場合?

+0

それは以下を返します: '{"成功 ":真、"メッセージ ":"生徒 ":\" TWlrZQpCb2I = \ "、\"サブ\ ":\"英語\ "、\" \ "テストトピック\"、\ "クラス\"、\ "テストクラス\"、\ "チェック\":\ "WzEsNSw5XQ == \"、\ "代名詞\":\ "2 \" }] "}' – user6790086

関連する問題