我正在开发基于ajax的网页设计作业。我遇到了JSON.parse()函数的问题。问题如下,我使用ajax在我的JSON数据库上执行get请求:
artist_list = $.ajax({
dataType: "json",
async: false,
method: "GET",
url: "/database/artists.json",
error: function (xhr) {
console.log("AJAX error:", xhr.status);
},
success: function(xhr, responseText) {
console.log("Ajax operation succseded the code was:", xhr.status);
console.log("This is the output", responseText);
response = responseText;
console.log("Parsing artist list");
JSON.parse(response);
console.log("Artist list parsed");
},
done: function(data, textStatus, jqXHR){
console.log("data:", data);
console.log("Response text",jqXHR.responseText);
}
})
responseText的控制台日志与我想要的JSON文件相匹配,但是, 当我通过for循环运行响应文本时,日志通过char:
返回JSON文件charartist_list = artist_list.responseText;
JSON.parse(artist_list);
console.log(artist_list);
for(var i = 0; i < 1; i++) {
console.log("generating artist,", i);
console.log("which is:", artist_list[i]);
index = parseInt(i);
index = new artist_lite(artist_list[i]);
artist_lite_dict.push(index);
}
控制台返回:
generating artist, 0
which is: {
由于我试图通过的JSON对象的长度,列表限制为一个。可以在此处找到JSON https://github.com/Stephan-kashkarov/Collector/blob/master/main/database/artists.json以及用于测试目的的整个代码。
感谢您的帮助! - 斯蒂芬
答案 0 :(得分:1)
您需要将JSON.parse(artist_list);
的结果保存到某个变量中。我想在你的代码中你想解决它:
artist_list = JSON.parse(artist_list);