有幾個問題,你的代碼這似乎缺乏的JS對象和對象屬性的理解幹。瞭解這些將爲您節省數小時的頭痛。
第一件事(小事一件)我想指出的是混合你的對象聲明。
var myObject = new Object();
// is the equivalent of:
var myObject = {};
類似與數組:
var myArray = new Array();
//is the equivalent of:
var myArray = [];
不要緊,你選擇去與模式(JS社區喜歡的[]和{}),但要確保你和你的方法是一致的。其次,將對象視爲關聯數組,即關鍵字 - >值對的列表。這些鍵被稱爲對象屬性。所以,所有對象都應該遵循以下模式:
// Note: each object property declaration is comma separated.
var myObject = {
propertyString: 'this is a string',
propertyAnotherString: 'this is another string',
propertyMixedArray: ['item 1', 'item 2', 1, 2, {}],
// Note above, we have different data types in the array:
// two strings, two ints and one empty object.
// This is completely legal in javascript.
propertyObject: { someProperty: 'and so on...' }
};
// Adding additional properties is OK too.
// Note: this time we use '=' instead of ':' to assign value
myObject.additionalProperty = 'Additional property';
// prints 'this is a string'
console.log(myObject.propertyString);
// also prints 'this is a string'
// I'm treating object as an associative array or hashtable
console.log(myObject['propertyString']);
// also prints 'this is a string'
// we can use variables as well to dynamically access keys.
var keyFromVariable = 'propertyString';
console.log(myObject[keyFromVariable]);
// Couple of other examples.
console.log(myObject.propertyMixedArray[1]); // prints 'item 2'
console.log(myObject.propertyObject.someProperty); // prints 'and so on...'
console.log(myObject.additionalProperty); // prints 'Additional property'
這可能是壓倒性的開始,但你會隨着時間的推移習慣了。但是,在編寫JavaScript代碼時,始終將您的想法始終放在頭腦中很重要。現在我們對對象有了更多的瞭解,我們可以用以下方式重寫您的代碼:
var myObject = {
EngineSpecs: [{
EngineID: 100010017,
Displacement: 7.2,
Gas: false
}, {
EngineID: 300200223,
Displacement: 3.2,
Gas: true
}]
};
$.ajax({
url: 'http://www.someurlhere.com/api.json',
dataType: "json",
data: myObject
});
我希望這會有所幫助。
除了答案和以前的評論,在你的ajax調用你設置數據:myObject,我認爲它應該是數據:data – TommyBs 2013-04-09 16:09:29
當在循環中填充屬性值時,這將如何工作?不覆蓋以前的條目? - 感謝 – SkyeBoniwell 2013-04-09 16:49:34