我有一個編碼的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);
}
}
});
警報一系列的響應[目標對象]秒。
使用'console.log'而不是警報(並檢查您的瀏覽器控制檯輸出)。 'Result.customers'是一個對象數組,這就是爲什麼alert會顯示你所看到的。 – bfavaretto 2013-05-03 18:05:38
從上面的示例數據看來,例如,客戶名稱可以使用:'Result.customers [i] .customer.customerName'來訪問。你的代碼只使用'Result.customers [i] .customerName'。臨時變量'customer'的名字隱藏了這個微妙之處。 – 2013-05-03 18:08:25
@JimCote,你的回答不是一個「答案」,所以我不能碰它,但在三天的抨擊我的頭骨,你的評論救了我! – BillyNair 2017-02-13 08:39:08