从数据库获取JSON数据后无法正常渲染展示的问题求助
问题根源:多余的
JSON.stringify()操作导致解析异常 你遇到的问题核心是错误地对responseText使用了JSON.stringify(),这完全是画蛇添足,反而把原本正确的JSON字符串变成了无法正常解析的转义字符串。
为什么会出错?
this.responseText本身就是服务器返回的JSON格式字符串,比如你的readTourData.php返回的是{"data":[{"ID":"1",...}]}- 而
JSON.stringify()的作用是把JavaScript对象转换成JSON字符串,你把一个JSON字符串丢进去,它会把这个字符串再包裹一层引号,变成类似"{\"data\":[{...}]}"的结构 - 这时候再用
JSON.parse()解析,得到的结果不是你想要的对象,而是原来的JSON字符串本身——你可以看看console.log(object2)的输出,它应该是一个带引号的长字符串,而不是对象结构,自然访问object2.data或者object2.title都会返回undefined
修正后的代码
直接去掉多余的JSON.stringify()步骤,直接解析responseText即可:
var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { // 直接解析responseText,不需要先stringify const tourData = JSON.parse(this.responseText); console.log(tourData); // 现在可以正常访问data数组里的元素了 console.log(tourData.data[0].title); // 应该输出"skijanje" // 把内容渲染到页面 document.getElementById("test").innerHTML = tourData.data[0].title; } }; xmlhttp.open("GET", "readTourData.php", true); xmlhttp.send();
额外优化建议
你还可以直接设置xhr.responseType = 'json',这样浏览器会自动帮你解析JSON,不需要手动调用JSON.parse():
var xmlhttp = new XMLHttpRequest(); xmlhttp.responseType = 'json'; // 加上这一行 xmlhttp.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { const tourData = this.response; // 直接拿到解析好的对象 console.log(tourData.data[0].title); document.getElementById("test").innerHTML = tourData.data[0].title; } }; xmlhttp.open("GET", "readTourData.php", true); xmlhttp.send();
这样代码更简洁,也避免了手动解析可能出现的错误。
内容的提问来源于stack exchange,提问作者Abu Machi
相关产品推荐
相关产品推荐

