[英]run ajax function on page load
嗨,我正在嘗試加載內容並在頁面上轉儲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(function(){
console.log('this is run on page load');
myFunction();
});
傳遞給addEventListener
事件類型應該沒有on
前綴。 代替addEventListener("onload", function () {
使用addEventListener("load", function () {
。
另外,您將事件偵聽器附加到變量body
,但是此變量未在代碼中定義。 如果文檔中具有id="body"
的元素(向后兼容的瀏覽器行為),它仍然可能起作用,但是我不會依賴此功能。
最好的解決方案是將整個代碼包裝在下面;
document.addEventListener("DOMContentLoaded", function(event) {
//do stuff here
});
DOM完成加載后,這將執行所有代碼。 幾乎所有瀏覽器都支持此功能,但實際上不再使用的瀏覽器(例如IE8)都支持。
您也可以僅通過調用函數來執行此操作,但是某些獲取DOM元素的變量如果尚未加載節點,則可能無法正確捕獲節點。
例如,完整的JS,也在JSFiddle中進行了測試。 工作正常。
document.addEventListener("DOMContentLoaded", function(event) {
var animalContainer = document.getElementById("animal-info");
var ourRequeast = new XMLHttpRequest();
var loaded = document.getElementById("body");
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');
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.