我很喜欢使用JS编程,所以这可能是一个愚蠢的问题,但经过几个小时的搜索后,我找不到网上的工作解决方案。
我有多个JSON Feed。服务器为每个URL提供一个多层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": "A.Pandy@beebhouse.com",
"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": "REFROOM@TBHOLDINGS.COM",
"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-function中的console.log输出打印了对象信息和&#34; ca_phone_mobile&#34;编号很好,但for循环中的第一个控制台输出说:&#34;未捕获TypeError:无法读取属性&#39; LGICUS01OperationResponse&#39;未定义的(...)&#34;。我是否需要一些toString数据类型转换或类似的?我也尝试将myjson数组传递给getCurrentJson函数,但没有成功。
答案 0 :(得分:0)
注意AJAX请求是异步的
PS:下面的部分示例(另请注意,并非所有请求都必须成功,有些可能会失败并且永远不会获得done == total
)
var myjson = [];
var total = 10;
var done = 0;
for (i = 1; i <= total; i++) {
getCurrentJson(i);
// at this point AJAX request haven't finished (most likely)
//console.log(myjson[i].LGICUS01OperationResponse.ca.ca_phone_mobile);
}
function allDone() {
console.log(myjson);
}
function getCurrentJson(current){
$.ajax({
dataType: "json",
url: "http://192.49.208.193:9081/ci/c/"+current,
success: function(data){
myjson[current] = data;
done++;
console.log(myjson[current]);
console.log(myjson[current].LGICUS01OperationResponse.ca.ca_phone_mobile);
if (done == total) {
allDone();
}
}
});
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
答案 1 :(得分:0)
Javascript是异步的,你必须等待响应。现在
console.log(myjson[i].LGICUS01OperationResponse.ca.ca_phone_mobile);
在收到你的ajax请求的响应之前执行。所以你应该使用async或处理回调。