2016-08-02 50 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

如果你只想使用'stringify',爲什麼不'JSON.stringify({[] })'? – eisbehr

+0

首先,「course ['name'] = $('#course')。val();」將會是「courses ['name'] = $('#course')。val();」 – Arnab003

回答

0

改變你的代碼如下

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

添加你做一個學生:

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

非常感謝你的工作很棒。如果我仍然需要在存儲這些值之前在服務器端解碼它,請問你有什麼想法嗎? – princesse

+0

取決於你的數據庫,你如何發送它們等等 – madalinivascu

+0

我通過ajax發送數據到處理腳本。我必須讓數據解包數據並將其存儲在兩個表格課程和學生中。 – princesse