我想根據我在 JQuery 中通過 AJAX 呼叫檢索到的“國籍”中的專案數量來遍歷 JSON 物件。問題是我的 JSON 物件中有一個陣列,我還需要回圈遍歷該陣列。目前我得到未定義或只能列印公司名稱。
我檢索到的 JSON 回應:
{"nationality":[{"country":"Spain","abbreviation":"es"},{"country":"Brazil","abbreviation":"br"}],"Company":"John Comp","errors":false,"meta":{"execution_time":"2.512342 seconds"}}
我想通過以下方式將這些列印在表格中:

我嘗試了什么:
$.ajax({
type: 'GET',
url: 'testurl',
success: function (response) {
var data = JSON.parse(response);
// How can I check if response here is empty if it is an JSON String?
if (response.length > 0) {
$.each(response.nationality, function (i, item) {
console.log(item.country);
}
uj5u.com熱心網友回復:
您正在決議資料變數中的回應,但您在回圈中使用回應變數而不是資料變數。
try {
const json = JSON.parse(response);
if(!json.nationality || !json.nationality.length === 0) throw new Error('Nationality is empty')
json.nationality.forEach((item)=>{
console.log(item)
//do your stuff
})
} catch (e) {
console.error(e)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/418579.html
標籤:
