gpt4 book ai didi

javascript - 在 javascript/jquery 中更改基于 xhttp.readyState 的元素文本

转载 作者:行者123 更新时间:2023-11-30 15:12:31 25 4
gpt4 key购买 nike

我有一个用户点击并从 PHP 页面下载的按钮,因为处理时间有点长,我想显示一个文本,向用户显示他们的请求正在处理,我找到了 onreadystatechange 可以访问属性,所以也许我可以将它用于任务。

ready StateHolds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

我的代码如下,我可以得到 readyState == 4 但不能得到 readyState == 3,任何建议都很好!

<button type="submit" class="btn btn-primary" id="weekDL">
<i class="fa fa-download"></i>
Download
</button>
<p id="please">Generating report, please wait..</p>
$('#weekDL').on('click',function(){
$(this).hide();
$('#please').show();
var data = $("#week option:selected").text();

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if(this.readyState == 3) {
$('#please').text('Request recieved..');
} else if (this.readyState == 4 && this.status == 200) {
window.location = "PHPexcel/download.php?week=" + data;
this.responseText;
$('#please').hide();
$('#weekDL').show();
}
};
xhttp.open("GET", "PHPexcel/download.php?week=" + data, true);
xhttp.send();
});
});

最佳答案

您的代码运行良好。问题是因为状态 3 仅在状态 4 出现之前存在几毫秒(取决于响应的大小),因此您的 UI 更新几乎察觉不到。

您可以通过将 console.log('state: ' + this.readyState); 放在 onchangereadystate 处理程序中来验证这一点。然后您将在控制台中看到所有 4 种状态的输出。

Working example

这当然是假设 AJAX 请求返回有效响应。如果请求中有错误,那么您只会看到状态 1 和 4。但是在这种情况下,问题出在请求中的逻辑上,而不是您的 JS。

关于javascript - 在 javascript/jquery 中更改基于 xhttp.readyState 的元素文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44898654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com