已向Controller传值并获取Ajax数组响应,如何遍历展示数据?
如何在Ajax中遍历数组响应并展示数据
嘿,我来帮你搞定这个遍历数组并展示数据的问题!首先得确保你的Ajax请求已经把响应正确转成了JavaScript数组——要么在请求里设置dataType: 'json'(如果用jQuery的话),要么手动用JSON.parse()解析返回的字符串。接下来就有几种简单好用的方法来处理啦:
方法1:用原生JS的forEach遍历
这是最常用的原生方式,简洁又直观:
// 假设你已经通过Ajax拿到了响应数据,存在responseData里 const responseData = [{"description":"Spring (03/01/2017 - 30/03/2017) - Training Fees","attandence_count":"0","pay":"£159.00"},{"description":"Spring (03/01/2017 - 30/03/2017) - Training Fees","attandence_count":"0","pay":"£159.00"},{"description":"Spring (03/01/2017 - 30/03/2017) - Training Fees","attandence_count":0,"pay":"£159.00"},{"description":"Spring (03/01/2017 - 30/03/2017) - Training Fees","attandence_count":0,"pay":"£159.00"}]; // 逐个遍历数组里的每个对象 responseData.forEach(item => { // 取出每个对象里的属性 const desc = item.description; const count = item.attandence_count; const pay = item.pay; // 比如创建一个div元素,把数据塞进去,再加到页面的容器里 const listItem = document.createElement('div'); listItem.innerHTML = ` <p><strong>描述:</strong> ${desc}</p> <p><strong>出勤次数:</strong> ${count}</p> <p><strong>费用:</strong> ${pay}</p> <hr> `; document.getElementById('result-container').appendChild(listItem); });
方法2:用jQuery的$.each(如果你的项目在用jQuery)
如果平时习惯用jQuery,它的遍历方法也很顺手:
// 同样假设responseData是Ajax返回的数组 $.each(responseData, function(index, item) { // 提取数据 const desc = item.description; const count = item.attandence_count; const pay = item.pay; // 直接把内容追加到页面的容器里 $('#result-container').append(` <div class="fee-item"> <p><strong>描述:</strong> ${desc}</p> <p>出勤次数: ${count} | 费用: ${pay}</p> <hr> </div> `); });
几个小提醒
- 页面里得先有个容器来放渲染后的内容哦,比如加个
<div id="result-container"></div>。 - 如果Ajax返回的是纯字符串,记得先转成数组——jQuery里设
dataType: 'json'会自动帮你转,原生JS的话就用JSON.parse(responseText)。 - 要是需要更复杂的渲染,也可以用模板引擎,但上面的方法足够应付大部分简单场景啦。
最后给你个完整的Ajax请求示例(jQuery版),把请求和遍历放一起:
$.ajax({ url: '/你的控制器地址', method: 'GET', dataType: 'json', // 自动解析JSON success: function(responseData) { // 请求成功就遍历渲染 $.each(responseData, function(index, item) { $('#result-container').append(` <div> <p>${item.description}</p> <p>出勤次数: ${item.attandence_count} | 费用: ${item.pay}</p> <hr> </div> `); }); }, error: function(xhr, status, error) { console.error('请求出错啦:', error); } });
内容的提问来源于stack exchange,提问作者Hardik Patel
相关产品推荐
相关产品推荐

