javascript - XMLHttpRequest,readyState 问题
问题描述
在网页中,我使用XMLHttpRequest。而且我遇到了麻烦,因为事情不会像往常一样发生。
以下是相关代码:
let xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Here useful work is done.
.......
}
}
xmlHttp.open("GET","readUser.php?EL="+user.email,true);
xmlHttp.send();
但最近由于某种原因,这种情况正在发生:
this.status == 200 (as expected)
但:
this.readyState == 3 (and not 4 as usual)
结果,“有用的工作”没有完成。
我怎样才能让“this.readyState”回到 4 ?
或者我怎样才能找到为什么“this.readyState”不是 4 应该的?
我使用 XMLHttpRequest 的经验相当有限,所以当这里出现问题时我有点迷失了。除了当我(独立地)运行“readUser.php?EL=somemail@example.com”时。没有问题,我没有看到任何问题。
我尝试过使用 Firefox、Chrome 和 Safari,得到相同的行为;所以我认为这不是浏览器相关的问题。
++++++供参考,readUser是一个PHP页面,这里是readUser.php中的相关代码
<?php
....
ConnectToDB();
$query = 'SELECT * FROM MyDBTable';
$query .= sprintf(" WHERE MlAdr='%s'",$_GET['EL']);
$DBS=$Connection->query($query);
$DBS->setFetchMode(PDO::FETCH_ASSOC);
$dataJSON = json_encode($DBS->fetch());
echo $dataJSON;
?>
解决方案
而不是xmlHttp.onreadystatechange
使用
xmlHttp.onload = function() {
if (this.status == 200) {
// Here useful work is done.
.......
}
}
xhr (XMLHttpRequest) 方法是 oldscool - 考虑使用更现代的方法:fetch。
推荐阅读
- if-statement - 如何将列表的元组与值进行比较?
- php - 在没有 ON CASCADE 的情况下准备多行 PHP 代码中的语句
- java - 可以帮我在java中执行sql
- docker - Ping 不会安装在 Docker 容器中
- django - DjangoRestFramework,我想要名称而不是 ID,
- c++ - 具有模板参数和 crtp 的类,仅按类名调用构造函数
- javascript - 像 SQL 一样使用 IndexedDB。使用不在范围内的多个索引值进行查询
- javascript - 通过在 URL 末尾附加一个变量来设置加载时的默认主题
- r - R: 为什么使用 download.file() 下载的 PNG 文件无法打开?
- java - 断字问题:没有得到负例的预期 O/P