有几个问题,你的代码这似乎缺乏的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