javascript - 在页面加载时运行 ajax 函数

标签 javascript jquery ajax

嗨,我正在尝试加载内容并在页面上转储 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>

ma​​in.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/

相关文章:

javascript - css 转换只能在 setInterval 内工作?为什么?

javascript - 显示滚动区域外的元素

jquery - 使弹出窗口仅在悬停几秒钟后出现

java - 如何从 JSF 中的 ActionListener 呈现表单的部分内容

javascript - 页面加载ajax Jquery mobile不显示

javascript - 单击此图像/链接激活 jquery 弹出窗口?

javascript - Puppeteer 按 Enter 按钮或单击 Dialog OK 按钮

javascript - ASP.NET AJAX 控制工具包文件上传在 Scriptresource.axd 中引发错误

javascript - 解释数组 - 连接到特定对象

javascript - 最好的叠加方式