我有一个编码的 JSON 对象,它存储一个对象数组,我希望遍历这些对象以便输入到数据库中。 Result 对象类似如下:
{
"customers": [
{
"customer": {
"id":"1",
"customerName":"Customer Alpha",
"customerID":" custA",
"customerAddress":" Alpha Way",
"customerCity":" Alpha",
"customerState":" AL",
"customerZip":"91605"
}
},
{
"customer": {
"id":"2",
"customerName":"Customer Beta",
"customerID":" CustB",
"customerAddress":" Beta Street",
"customerCity":" Beta",
"customerState":" BE",
"customerZip":"91605"
}
}
]
}
我希望能够将每个字段输入到数据库中,但是我的代码将未定义的所有内容输入到数据库中。访问数组中每个字段中存储的变量的正确方法是什么?
这是我目前使用的不起作用的方法:
function insertCustomer(customerName, customerID, customerAddress, customerCity, customerState, customerZip) {
db.transaction(function (tx) {
tx.executeSql('INSERT INTO Customers (customerName, customerID, customerAddress, customerCity, customerState, customerZip) VALUES (?, ?, ?, ?, ?, ?)', [customerName, customerID, customerAddress, customerCity, customerState, customerZip], CountReturns);
});
};
$.ajax({
url : 'http://webserver/retrieveDatabase.php',
dataType : 'json',
type : 'get',
success : function(Result){
alert(Result.customers);
for (var i = 0, len = Result.customers.length; i < len; ++i) {
var customer = Result.customers[i];
insertCustomer(customer.customerName, customer.customerID, customer.customerAddress, customer.customerCity, customer.customerState, customer.customerZip);
}
}
});
警报以一系列 [object Object] 响应。
最佳答案
改变
var customer = Result.customers[i];
到
var customer = Result.customers[i].customer;
关于javascript - 使用 Javascript 访问 JSON 对象中数组中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16365029/