我最近一直在尝试 MyJSON 。我试图创建一个从数据库中获取数据的函数(这样我就不必每次需要时都输入长文本),但每当我运行代码时,我的页面就会突然卡住。根据我的调试,它甚至在卡住之前不运行代码。这是我的 IDE 的错误吗?如果有帮助,我正在使用 repl.it使用 HTML/CSS/JS。
function submit() {
}
console.log("test test test");
function getJSON() {
console.log("beginning");
var out;
console.log("start");
$.get("https://api.myjson.com/bins/1fsm75", function(data, textStatus, jqXHR) {
var json = JSON.stringify(data);
console.log(json);
out = json;
console.log(out);
});
while(out == undefined) {}
return out;
}
console.log("testarooni");
console.log(getJSON());
最佳答案
为了解决您遇到的问题,我建议检查浏览器中的网络选项卡(在 Google Chrome 中按 F12 调出它),以便了解 GET 调用的具体性能。
我还想建议,无论如何,使用异步调用执行相同的调用。 异步 GET 调用是首选,因为它是非阻塞的。
以下是从您提供的端点检索数据的异步 GET 调用示例:
<!DOCTYPE html>
<html>
<head>
<script>
async function getDataAsync() {
let response = await fetch('https://api.myjson.com/bins/1fsm75');
let data = await response.json()
return data;
}
getDataAsync()
.then(data => console.log(data));
</script>
</head>
<body>
</body>
</html>
关于javascript - 页面因未知原因卡住,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58083461/