2016-08-02 7 views
0

おはようございます!オブジェクトリテラルをオブジェクト内の配列に挿入する

var persons = {};// I want all the objects in the array to be inserted here so that I can stringify it and send via Ajax 
 
var array = [];// where I store the object literals 
 
var courses = {}; 
 
course['name'] = $('#course').val(); 
 
array.push(courses); 
 
var students = {}; 
 
students['first'] = $('#first_name').val(); 
 
students['last'] = $('#last_name').val(); 
 
students['age'] = $('age').val(); 
 
array.push(courses); 
 
// I tried this after the help I got this morning but it does not create multiple objects. When there are many successive values, the data sent is empty 
 
var persons = { 
 
    courses: { 
 
     name: $('#course').val(), 
 
    }, 
 
    students: { 
 
     name: $('#first_name').val(), 
 
     last: $('#last_name').val(), 
 
     age: $('#age').val(), 
 
    }, 
 
};

誰もが、私はいくつかの学生を作成する方法を知っているし、当然と同じオブジェクトでそれらを持っていないしてください は、私は、フォームの値からオブジェクトリテラルを生成し、次のように私は、配列に格納します名?

+0

を、なぜだけではなく、' JSON.stringify({[] }) '? – eisbehr

+0

まず、 "course ['name'] = $( '#course')。val();" "コース['name'] = $( '#コース')。val();" – Arnab003

答えて

0

courses = { 
     name: $('#course').val(), 
     students: [] 
}; 

を次のようにあなたが学生を追加するようにコードを変更:あなたが唯一の `stringify`を使用したい場合は

courses.students.push({ 
     name: $('#first_name').val(), 
     last: $('#last_name').val(), 
     age: $('#age').val(), 
    }) 
+0

ありがとうございます。値を保存する前にまだサーバー側でそれを解読する必要がある場合、あなたはどんな考えを持っていますか? – princesse

+0

はデータベースに依存し、送信方法などは – madalinivascu

+0

です。データをajax経由で処理スクリプトに送信しました。データを解凍して、2つのテーブルのコースと生徒に保存する必要があります。 – princesse