我有這樣的JSON結果:訪問通過JSON AJAX數組中的數據 - >對象
[{
"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);
}
nhs_hospitals的內容是什麼? –
問題在於'nhs_hospitals'對象裏面有'result'數組。如果你引用它,你應該得到結果,因爲我已經發布在 – nikjohn