You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

jQuery处理PHP AJAX响应时遍历数据数组报错求助

解决AJAX获取JSON后遍历数组异常的问题

嘿,我一眼就看到问题出在哪了——你重复解析JSON啦!

你在AJAX配置里已经设置了dataType: "json",这意味着jQuery会自动帮你把服务器返回的JSON字符串转换成JavaScript对象。这时候success回调里的response已经是一个现成的对象了,你再调用$.parseJSON(response)就会触发错误,因为你没法对一个JavaScript对象做JSON解析操作。

修正后的代码

只需要删掉那行多余的解析代码,直接使用response就行:

var url = $("#url").val();
var type = 'F';
var data_url = url + "manage/sources/ajax/ajax.php?type=GetBarber&gender=" + type ;
$.ajax({
    type: "GET",
    url: data_url,
    dataType: "json",
    success: function (response) {
        // 这里response已经是解析好的对象,直接用就行
        for (let i = 0; i < response.data.length; i++) {
            var payment = response.data[i];
            console.log(payment); // 现在应该能正常打印name541、name214了
        }
    },
    // 建议加上error回调,方便排查请求或解析时的错误
    error: function(xhr, status, error) {
        console.error("请求出现问题:", error);
    }
});

额外小优化

用数组的forEach方法遍历会更简洁:

response.data.forEach(function(name) {
    console.log(name);
});

补充说明

  • 当你设置dataType: "json"时,jQuery会自动检查服务器响应的Content-Type头是否为application/json,如果符合就自动完成解析。
  • 如果你没设置dataType,服务器返回的是原始字符串,这时候才需要用$.parseJSON()去手动解析。

内容的提问来源于stack exchange,提问作者Dani Prime

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:32:12