我有一个编码的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] 的形式做出响应。
console.log
代替 alert(并检查您的浏览器控制台以获取输出)。Result.customers
是一个对象数组,这就是为什么alert显示您所看到的内容。 - bfavarettoResult.customers[i].customer.customerName
。但是您的代码仅使用了Result.customers[i].customerName
。临时变量customer
的名称隐藏了这种微妙之处。 - Jim Cote