我很漂亮n00b與JS編程,所以這可能是一個愚蠢的問題,但經過幾個小時的搜索,我還沒有找到一個工作的解決方案。閱讀多個JSon記錄到一個數組
我有多個JSON訂閱源。服務器是給一個多層JSON創紀錄的網址是這樣的(數據是虛構的測試數據):
-
{ "LGICUS01OperationResponse": { "ca": { "ca_phone_mobile": "07799 123456", "ca_request_id": "01ICUS", "ca_return_code": 0, "ca_dob": "11.07.1950", "ca_last_name": "Pandy", "ca_num_policies": 0, "ca_phone_home": "01962 811234", "ca_email_address": "[email protected]", "ca_house_name": "", "ca_policy_data": "", "ca_customer_num": 1, "ca_first_name": "Andrew", "ca_house_num": "34", "ca_postcode": "PI101OO" } } }
-
{ "LGICUS01OperationResponse": { "ca": { "ca_phone_mobile": "123", "ca_request_id": "01ICUS", "ca_return_code": 0, "ca_dob": "30.09.1965", "ca_last_name": "Tracey", "ca_num_policies": 0, "ca_phone_home": "", "ca_email_address": "[email protected]", "ca_house_name": "Tracey Island", "ca_policy_data": "", "ca_customer_num": 2, "ca_first_name": "Scott", "ca_house_num": "", "ca_postcode": "TB14TV" } } }
等。現在我設法用ajax讀取JSON recors,但是我有嚴重的問題在getCurrentJson函數之外傳遞這些信息。最佳的情況是,所述第一兩個參數將被省略,以便不會有供以後操作的用戶信息的「標準方式」的陣列是這樣的:
{
"rows":[
{"ca_customer_num":1", "ca_first_name:"Andrew",...}
{"ca_customer_num":2", "ca_first_name:"Scott",...}
...
]
}
下面是代碼:
<!DOCTYPE html>
<html>
<head>
<title>JSON test</title>
<script src="jquery.js" type="text/javascript"></script>
<script>
var myjson = [];
for (i = 1; i < 11; i++) {
getCurrentJson(i);
console.log(myjson[i].LGICUS01OperationResponse.ca.ca_phone_mobile);
}
function getCurrentJson(current){
$.ajax({
dataType: "json",
url: "http://192.49.208.193:9081/ci/c/"+current,
success: function(data){
myjson[current] = data;
console.log(myjson[current]);
console.log(myjson[current].LGICUS01OperationResponse.ca.ca_phone_mobile);
}
});
}
</script>
</head>
<body>
</body>
</html>
現在,ajax函數內部的console.log輸出顯示Object信息和「ca_phone_mobile」數字,但for循環中的第一個控制檯輸出顯示:「Uncaught TypeError:無法讀取undefined(...)的屬性'LGICUS01OperationResponse' 」。我是否需要一些toString數據類型轉換或類似的?我也嘗試將myjson數組傳遞給getCurrentJson函數,但沒有成功。
'$ .ajax'執行異步調用。這就是爲什麼你for循環中的'console.log'沒有顯示預期的結果,異步請求還沒有完成。 –