11

我有一个编码的 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] 响应。

4

2 回答 2

8

改变

var customer = Result.customers[i];

var customer = Result.customers[i].customer;
于 2013-05-03T18:09:19.170 回答
1

您可以像这样处理 JSON 对象:

for(var key in Result["customers"]) {
   // examples
   console.log( Result[key].customer );
   console.log( Result[key]["customer"] );
   console.log( Result[key]["customer"].customerID );
}
于 2013-05-03T18:23:15.027 回答