Javascript 它没有';t使用fetch call在屏幕上打印名称
我需要帮助,我必须使用fetch call从给定的url调用数据。它应该在屏幕上打印学院名和学生名,但当我点击按钮时,什么也没发生。我知道这可能是一个有点庞大的代码,它需要时间,但如果有人能帮助我,我将不胜感激。提前感谢:) $(文档).ready(函数(){Javascript 它没有';t使用fetch call在屏幕上打印名称,javascript,fetch,Javascript,Fetch,我需要帮助,我必须使用fetch call从给定的url调用数据。它应该在屏幕上打印学院名和学生名,但当我点击按钮时,什么也没发生。我知道这可能是一个有点庞大的代码,它需要时间,但如果有人能帮助我,我将不胜感激。提前感谢:) $(文档).ready(函数(){ 函数打印学生(响应学生){ 让h1Element=$(`).text(${responseStudents.academy}); 设uList=$(``); $(“正文”).append(h1元素,uList); 对于(i=0;i
函数打印学生(响应学生){
让h1Element=$(`).text(${responseStudents.academy});
设uList=$(`
`);
$(“正文”).append(h1元素,uList);
对于(i=0;i${responseStudents.students[i]}`);
}
}
$(“#按钮”)。单击(函数(){
取回(“https://raw.githubusercontent.com/Drakso/AJS2019/master/Class1/students.json")
.然后(功能(响应){
返回response.json();
})
.then(功能(数据){
//让responseStudents=JSON.parse(response);
//打印学生(回应学生);
console.log(数据)
},).catch(函数(错误){
警报(“未找到用户”);
})
})
})嘿,以下几点应该适合你:- 您试图访问
response
(我在这里作为data
)对象而不是students
数组的length
属性,因此循环没有运行
$(文档).ready(函数(){
函数(数据){
让h1Element=$(``).text(`${data.academy}`);
设uList=$(`
`);
让responseStudents=data.students;
$(“正文”).append(h1元素,uList);
对于(i=0;i${responseStudents[i]}`);
}
}
$(“#按钮”)。单击(函数(){
取回(“https://raw.githubusercontent.com/Drakso/AJS2019/master/Class1/students.json")
.然后(功能(响应){
返回response.json();
})
.then(功能(数据){
打印学生(数据);
},).catch(函数(错误){
警报(“未找到用户”);
})
})
})
单击“我”
code应该可以工作,可能您没有为DOM元素添加id
?您在浏览器控制台中看到任何错误吗?我能够获取数据并将其记录在控制台日志中。@LakshyaThakur我没有任何错误,是的,它们出现在控制台日志中,但我需要它们在浏览器上,而不是控制台日志中。
function printStudents(responseStudents) {
let h1Element = $(`<h1></h1>`).text(`${responseStudents.academy}`);
let uList = $(`<ul></ul>`);
$("body").append(h1Element, uList);
for (i = 0; i < responseStudents.length; i++) {
uList.append(`<li> ${responseStudents.students[i]}</li>`);
}
}
$("#button").click(function () {
fetch ("https://raw.githubusercontent.com/Drakso/AJS2019/master/Class1/students.json")
.then (function (response) {
return response.json();
})
.then (function (data) {
//let responseStudents = JSON.parse(response);
//printStudents(responseStudents);
console.log(data)
},).catch (function (error) {
alert("USer not found");
})
})