【发布时间】:2021-11-28 02:33:35
【问题描述】:
我尝试遍历 JSON 对象,但它不起作用。有没有更有效的方法来构建对象?另外,我不确定是否正在发出 AJAX 请求,因为我不断看到一条错误消息,即“出现问题:0”。
这是我的 JS 文件:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "lab4.json",
dataType: "json",
success: function(response){
var message = "";
$.each(responseData.text, function(i, item) {
$.each(item.tutoring-text, function(x, s) {
message += s;
});
});
$("#tutoring-text").html(message);
},
error: function(msg) {
// there was a problem
alert("There was a problem: " + msg.status + " " + msg.statusText);
}
});
});
这是我的 JSON 文件:
{
"text":{
"tutoring-text": [
"Gamma Nu Eta holds weekly tutoring sessions every Wednesday.",
"At these tutoring sessions, GNH can help you with any course in your ITWS degree program.",
"This includes ITWS core classes, such as Intro to ITWS and Web Systems, or classes outside of ITWS, such as Computer Science 1 and Data Structures.",
"We can also help with any questions that you might have about career development, resumes, as well as just general questions about RPI."
]
}
}
【问题讨论】:
-
请注意,代码图像是问题中最没有帮助的内容之一(强烈建议不要使用指向主要信息的外部链接)。
-
这需要一个
jquery标签。 -
错误是什么?
-
0 error也会在控制台中显示错误消息。始终查看浏览器的控制台。最有可能是Access to XMLHttpRequest at 'file:///.../lab4.json' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.- 如果它是这条消息,那是因为你试图从本地文件运行ajax。您的文件必须由服务器提供(在本地主机上可以)。
标签: javascript html jquery json ajax