目前正在学习AJAX。
我正在测试 XMLHttpRequest 以在单击按钮时加载 json,但它似乎在任何单击发生之前先加载 json。
我也尝试过使用 append(this.responseText) 来查看它是否会在我每次单击按钮时附加 json,但这也不起作用。
function loadDoc(str) {
let xhttp = new XMLHttpRequest()
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.querySelector("#container").innerHTML = this.responseText;
}
};
xhttp.open('GET', "https://jsonplaceholder.typicode.com/posts/" + str, true);
xhttp.send();
}
let run = document.querySelector('#clickme');
run.addEventListener('click', loadDoc(2));
<html>
<head>
<meta charset="UTF-8">
<title>posts</title>
</head>
<body>
<div id="container">
</div>
<button id="clickme"> click me</button>
</body>
</html>