嗨,我正在尝试加载内容并在页面上转储 json: index.html
<html>
<head>
<title>Learning</title>
<style type="text/css">
body { background-color: #ddd; }
#container { height: 100%; width: 100%; display: table; }
#inner { vertical-align: middle; display: table-cell; }
#gauge_div { width: 120px; margin: 0 auto; }
</style>
</head>
<body id="body">
<script src="main.js"></script>
<div id="animal-info"></div>
</body>
</html>
main.js
var animalContainer = document.getElementById("animal-info");
var ourRequeast = new XMLHttpRequest();
var loaded = document.getElementById("body");
body.addEventListener("onload", function(){
ourRequeast.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json');
ourRequeast.onload = function() {
// console.log(ourRequeast.responseText);
// var ourData = ourRequeast.responseText;
var ourData = JSON.parse(ourRequeast.responseText);
// console.log(ourData[0])
renderHTML(ourData);
}
ourRequeast.send();
});
function renderHTML(data){
animalContainer.insertAdjacentHTML('beforeend', 'testing 123');
}
所以我希望它应该在页面加载时打印“testing 123”,但既不给出错误也不显示任何内容
最佳答案
您将需要使用 document ready statement
$(document).ready(function(){
console.log('this is run on page load');
myFunction();
});
关于javascript - 在页面加载时运行 ajax 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41641058/