Uncaught SyntaxError: Unexpected token { in JSON at position 25
at JSON.parse (<anonymous>)
at XMLHttpRequest.responseFUN (file:///E:/javaScript/JavaScript200320501017/%E5%AE%9E%E9%AA%8C%E5%8D%81/zwj/artist(1).js:25:32)
猜测是httpRequest.responseText的值不是json格式
这个是JSON转换错了吧,是JSON.parse()转的数据不规范吗
你的json格式不标准导致的把数据发出来看看
代码书写错误,例如标点符号等
window.onload = ajaxRequest;
// console.log(window.location.href);
var strLocation = window.location.href;
var artistId = strLocation.substring(strLocation.lastIndexOf("=") + 1);
var API_URL = "http://39.98.85.248:3002/artist/top/song?id=" + artistId;
//ajax的网络请求
function ajaxRequest() {
//1.建立一个XMLHttpRequest对象实例
var httpRequest = new XMLHttpRequest;
//2.设置onreadystatechange属性
httpRequest.onreadystatechange = responseFUN
//3.建立或打开http请求
httpRequest.open("GET", API_URL);
//4.发送请求
httpRequest.send();
//处理服务器的响应
function responseFUN() {
//处理服务器响应
if (httpRequest.readyState == XMLHttpRequest.DONE) {
if (httpRequest.status == 200) {
//状态码是200,代表响应成功
//console.log(httpRequest.responseText);
var obj = JSON.parse(httpRequest.responseText);
success(obj);//利用响应成功的函数
} else if (httpRequest.status == 404) {
alert("Not Found")
} else if (httpRequest.status == 500) {
alert("Internal Server Error")
} else {
alert("其他问题")
}
}
};
}
function success(obj) {
console.log(obj);
var arr_songs = obj.songs;
var ele_ul = document.createElement("ul");
for (let i = 0; i < arr_songs.length; i++) {
const element = arr_songs[i];
//console.log(element.name);
var ele_li = document.createElement("li");
var ele_img = document.createElement("img");
var ele_span = document.createElement("span");
ele_span.innerHTML = element.name;
ele_img.setAttribute("src", element.al.picUrl);
ele_li.appendChild(ele_img);
ele_li.appendChild(ele_span);
ele_ul.appendChild(ele_li);
}
document.body.appendChild(ele_ul)
这是js代码 一直报错这一行 var obj = JSON.parse(httpRequest.responseText);