首页 > 解决方案 > 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;
?>

标签: javascriptxmlhttprequest

解决方案


而不是xmlHttp.onreadystatechange使用

xmlHttp.onload = function() {
  if (this.status == 200) {
    // Here useful work is done.
    .......
  }
}

xhr (XMLHttpRequest) 方法是 oldscool - 考虑使用更现代的方法:fetch


推荐阅读