我有这个json结果:
[{
"website": "http://www.rlbuht.nhs.uk",
"sub_type": "Hospital",
"sector": "NHS Sector",
"postcode": "L3 5PS",
"phone": "0151 706 2000",
"partial_postcode": "L3",
"parent_o_d_s_code": "RQ6",
"parent_name": "Royal Liverpool and Broadgreen University Hospitals NHS Trust",
"organisation_type": "Hospital",
"organisation_status": "Visible",
"organisation_name": "Royal Liverpool University Dental Hospital",
"organisation_id": "41513",
"organisation_code": "RQ614",
"longitude": "-2.9669923782348633",
"latitude": "53.408927917480469",
"is_pims_managed": "True",
"fax": "0151 706 5806",
"email": "",
"county": "Merseyside",
"city": "Liverpool",
"address3": "",
"address2": "",
"address1": "Pembroke Place"
}]
这是我的代码来访问url并获得正常工作的json:
$("#search_hospitals").on('click', function(p_oEvent_search_hospitals) {
var api_search_hospitals, postcode, nhs_hospitals;
p_oEvent_search_hospitals.preventDefault();
postcode = $('#input_nhs_h').val();
api_search_hospitals = 'https://data.gov.uk/data/api/service/health/hospitals/partial_postcode?partial_postcode=' + postcode;
$.ajax(api_search_hospitals, {
complete: function(p_OXHR, p_sStatus) {
nhs_hospitals = $.parseJSON(p_OXHR.responseText);
alert(nhs_hospitals[0].postcode);
}
});
});
我只是使用alert(nhs_hospitals[0].postcode);
进行测试,看看我是否可以获取数据,但我总是得到TypeError: undefined is not an object (evaluating 'nhs_hospitals[0].postcode')
...
有人可以帮助我说出我做错了什么,为什么我会得到"未定义"?谢谢
为了让我更容易:
complete: function(p_OXHR, p_sStatus) {
nhs_hospitals = $.parseJSON(p_OXHR.responseText);
hospital = nhs_hospitals.result[0];
alert(hospital.postcode);
}
答案 0 :(得分:2)
$('button').on('click', function(p_oEvent_search_hospitals) {
var api_search_hospitals, postcode, nhs_hospitals;
p_oEvent_search_hospitals.preventDefault();
postcode = 'EC1A'
api_search_hospitals = 'https://data.gov.uk/data/api/service/health/hospitals/partial_postcode?partial_postcode=' + postcode;
$.ajax(api_search_hospitals, {
complete: function(p_OXHR, p_sStatus) {
nhs_hospitals = $.parseJSON(p_OXHR.responseText);
console.log(nhs_hospitals);
alert(nhs_hospitals.result[0].postcode);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>search</button>
这应该有效。问题是nhs_hospitals
对象里面有一个result
数组。如果你参考,你会得到你的结果。
答案 1 :(得分:1)
做一个,
console.log(nhs_hospitals)
并查看是否打印数组,如果没有则表示p_OXHR.responseText
不包含任何内容。您确定responseText
是从服务器发送的内容吗?
答案 2 :(得分:0)
试一试:
$.ajax(api_search_hospitals, {
success: function (data) {
nhs_hospitals = $.parseJSON(data);
alert(nhs_hospitals[0].postcode);
}
});