2013-05-03 141 views
8

我有一个编码的JSON对象,它存储了我想要通过输入到数据库中的对象的数组。结果对象是类似如下:使用JavaScript在JSON对象内访问数组内的对象

{ 
    "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); 
     } 
     } 
    }); 

警报一系列的响应[目标对象]秒。

+0

使用'console.log'而不是警报(并检查您的浏览器控制台输出)。 'Result.customers'是一个对象数组,这就是为什么alert会显示你所看到的。 – bfavaretto 2013-05-03 18:05:38

+1

从上面的示例数据看来,例如,客户名称可以使用:'Result.customers [i] .customer.customerName'来访问。你的代码只使用'Result.customers [i] .customerName'。临时变量'customer'的名字隐藏了这个微妙之处。 – 2013-05-03 18:08:25

+0

@JimCote,你的回答不是一个“答案”,所以我不能碰它,但在三天的抨击我的头骨,你的评论救了我! – BillyNair 2017-02-13 08:39:08

回答

7

变化

var customer = Result.customers[i]; 

var customer = Result.customers[i].customer; 
+0

耶谢谢你。有用! =) – EzAnalyst 2013-05-03 18:15:38

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); 
}