我无法设置jquery ajax方法的data属性来包含一个具有名为EngineSpecs属性的javascript对象。
我想出了类似这样的东西来测试,但它不起作用:
var myObject = new Object();
myObject.EngineSpecs = {};
var data = {
myObject.EngineSpecs : [{
EngineID: 100010017,
Displacement: 7.2,
Gas: false
}, {
EngineID: 300200223,
Displacement: 3.2,
Gas: true
}]
};
$.ajax({
url: someurl,
dataType: "json",
data: myObject
我一直收到如下错误:
消息":"发生了错误。"," ExceptionMessage":"无法反序列化当前的JSON对象
非常感谢任何帮助!
答案 0 :(得分:1)
您正在尝试使用myObject.EngineSpecs
作为对象属性名称,这是不允许的(因为中间的。)。这样做:
var data = {
myObject: {
EngineSpecs : [{
EngineID: 100010017,
Displacement: 7.2,
Gas: false
}, {
EngineID: 300200223,
Displacement: 3.2,
Gas: true
}]
}
};
或者你真正想要的是:
var myObject = {
EngineSpecs : [{
EngineID: 100010017,
Displacement: 7.2,
Gas: false
}, {
EngineID: 300200223,
Displacement: 3.2,
Gas: true
}]
};
答案 1 :(得分:1)
您的代码存在一些问题,这些问题似乎源于对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
});
我希望这会有所帮助。