加载窗口时从服务器获取值



我希望在从服务器端获取数据后打开窗口时立即加载它。

这是HTML:

<body>
<h1> Just another counter </h1>
<div class="count-area">
<button type="button" onClick="increment()"> + </button>
<button type="button" onClick="decrement()"> - </button>
<p>Count: <a id="clicks">0</a></p>
</div>
</body>
</html>

这是客户端javascript:

window.onload = function() {
fetch("/").then(response => response.json()).then(data => document.getElementById("clicks").innerHTML = data['clicks']);
};
function increment() {
fetch("/increment").then(response => response.json()).then(data => document.getElementById("clicks").innerHTML = data['clicks']);
};
function decrement() {
fetch("/decrement").then(response => response.json()).then(data => document.getElementById("clicks").innerHTML = data['clicks']);
};

按下递增-递减按钮后,会显示正确的计数,但在此之前,计数保持为0。

不要使用windows.onload,而是尝试在body上使用onload="myFunction()"

function clicksLoad() {
fetch("/").then(response => response.json()).then(data => document.getElementById("clicks").innerHTML = data['clicks']);
};
function increment() {
fetch("/increment").then(response => response.json()).then(data => document.getElementById("clicks").innerHTML = data['clicks']);
};
function decrement() {
fetch("/decrement").then(response => response.json()).then(data => document.getElementById("clicks").innerHTML = data['clicks']);
};
<body onload="clicksLoad()">
<h1>Just another counter</h1>
<div class="count-area">
<button type="button" onClick="increment()">+</button>
<button type="button" onClick="decrement()">-</button>
<p>Count: <a id="clicks"></a></p>
</div>
</body>

最新更新