当readyState为4时,为什么我在脚本中调用的Ajax函数连续运行两次?

JDe*_*age 5 javascript php ajax

所有,

我正在使用Head First Ajax书来学习Ajax.在第一章中,他们给出了一些我简化了一些代码示例.我添加了一堆alert来了解发生了什么.这是代码:

HTML + Ajax(index.php):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Rob's Rock 'n' Roll Memorabilia</title>
<link rel="stylesheet" href="css/default.css" />
<script>
  function createRequest() {
    try {
      request = new XMLHttpRequest();
    } catch (tryMS) {
      try {
        request = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (otherMS) {
        try {
          request = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (failed) {
          request = null;
        }
      }
    }
  return request;
}

function getDetails(img){
  var title = img.title;
  alert("getDetails1");
  request = createRequest();
  alert("getDetails2");
  if (request == null) {
    alert("Unable to create request");
    return;
  }
  var url= "getDetails.php?ImageID=" + escape(title);
  alert("getDetails3");
  request.open("GET", url, true);
  alert("getDetails4");
  request.onreadystatechange = displayDetails;
  alert("getDetails5");
  request.send(null);
  alert("getDetails6");
}

function displayDetails() {
  alert("displayDetails1");
  if (request.readyState == 4) {
    alert("Request.readyState is 4");
    if (request.status == 200) {
      alert("Request.status is 200");
      detailDiv = document.getElementById("description");
      alert("displayDetails2");
      detailDiv.innerHTML = request.responseText;
      alert("displayDetails3");
    }else{
      alert("Request.status not 200");
      return;
    }
  }else{
    alert("Request.readystate not 4");
    return;
  }
}
</script>  
</head>
<body>
  <div id="wrapper">
    <div id="thumbnailPane">  
      <img src="images/SISL_Avatar2.JPG"
           title="SISL" id="SISL" onclick="getNextImage()" />  
      <img src="images/itemGuitar.jpg" width="301" height="105" alt="guitar" 
           title="itemGuitar" id="itemGuitar" onclick="getDetails(this)"/>
      <img src="images/itemShades.jpg" alt="sunglasses" width="301" height="88" 
           title="itemShades" id="itemShades" onclick="getDetails(this)" />
      <img src="images/itemCowbell.jpg" alt="cowbell" width="301" height="126" 
           title="itemCowbell" id="itemCowbell" onclick="getDetails(this)" />
      <img src="images/itemHat.jpg" alt="hat" width="300" height="152" 
           title="itemHat" id="itemHat" onclick="getDetails(this)" />
    </div>

    <div id="detailsPane">
      <img src="images/blank-detail.jpg" width="346" height="153" id="itemDetail" />
      <div id="description"></div>
    </div>

  </div>
</body>
</html>

<?php    
$details = array (
    'itemGuitar'    =>  "<p>Pete Townshend once played this guitar while his own axe was in the shop having bits of drumkit removed from it.</p>",
    'itemShades'    =>  "<p>Yoko Ono's sunglasses. While perhaps not valued much by Beatles fans, this pair is rumored to have been licked by John Lennon.</p>",
    'itemCowbell'   =>  "<p>Remember the famous \"more cowbell\" skit from Saturday Night Live? Well, this is the actual cowbell.</p>",
    'itemHat'       =>  "<p>Michael Jackson's hat, as worn in the \"Billie Jean\" video. Not really rock memorabilia, but it smells better than Slash's tophat.</p>"
);    
if (isset($_REQUEST['ImageID'])){echo $details[$_REQUEST['ImageID']];}
?>
Run Code Online (Sandbox Code Playgroud)

这是Ajax(getDetails.php)调用的URL :

<?php

$details = array (
    'itemGuitar'    =>  "<p>Pete Townshend once played this guitar while his own axe was in the shop having bits of drumkit removed from it.</p>",
    'itemShades'    =>  "<p>Yoko Ono's sunglasses. While perhaps not valued much by Beatles fans, this pair is rumored to have been licked by John Lennon.</p>",
    'itemCowbell'   =>  "<p>Remember the famous \"more cowbell\" skit from Saturday Night Live? Well, this is the actual cowbell.</p>",
    'itemHat'       =>  "<p>Michael Jackson's hat, as worn in the \"Billie Jean\" video. Not really rock memorabilia, but it smells better than Slash's tophat.</p>"
);
echo $details[$_REQUEST['ImageID']];
?>
Run Code Online (Sandbox Code Playgroud)

问题:为什么函数displayDetails在readystate 4运行两次?

当我运行上面的代码时,代码似乎运行displayDetails()两次.我首先得到displayDetails1警报信号,我已进入该功能.然后我得到与readyState不是4 相关的警报,然后再不是4,然后是4(Request.readyState is 4).然后状态警报告诉我状态是200.到目前为止,没有任何意外.

在那之后我得到一些奇怪的东西. 我收到displayDetails2警报,然后根据功能修改页面,我收到displayDetails3警报.然后我期望退出该功能.相反,我再次得到displayDetails1,Request.readyState is 4(第二次!)Request.status is 200,displayDetails2displayDetails3警报,如果整个函数已经运行一次.这是为什么?

PS:
1)在第二轮之后,我得到了getDetails6我期待的警报.
2)页面按原样运行 - 从用户的角度来看,如果禁用警报,则没有任何异常.3)我在WampServer上本地开发WinXP机器(我知道......).
4)如果我添加:

function alert(msg) {
  console.log(msg);
}
Run Code Online (Sandbox Code Playgroud)

在我的脚本中,日志只注册一个readyState is 4...

解析度

我做了3次测试:
1 - 只有警报,我收到两个readyState is 4警报.
2 - 如果我记录警报,则日志仅显示一个readyState is 4警报.
3 - 如果我同时记录并显示警报弹出窗口(使用此功能),我会收到两个readyState is 4警报(日志显示).

我对此的看法是,警报本身会导致脚本执行延迟并导致函数有效运行两次.

Jef*_*ows 6

javascript alert正在阻止你的UI线程,可能足够长的时间让你的浏览器完成加载AJAX请求.由于您未request.readyState在警报之后检查,因此可以在检查之前通过浏览器进行更新.

尝试修改事件处理程序:

function displayDetails() {
  var rs = request.readyState;
  alert("displayDetails1");
  if (rs == 4) {
    alert("Request.readyState is 4");
    //rest of code...
Run Code Online (Sandbox Code Playgroud)

您将看到"Request.readyState is 4"的一个警报


hek*_*mgl 5

onreadystatechange事件的请求时完成后,不仅引发.为XMLHttpRequest定义了5个状态:

  • 0未初始化初始值.
  • 1打开已成功调用open()方法.
  • 2已发送UA已成功完成请求,但尚未收到任何数据.
  • 3在接收消息正文(如果有)之前立即接收.已收到所有HTTP标头.
  • 4加载

通常在开发AJAX应用程序时,您只对4加载状态感兴趣,因为它意味着请求已完成,但您可以观察到其他状态.

因此,您不必担心第二次调用事件处理程序.这是正常行为.它只是意味着请求在其工作期间改变了其内部状态.

如果您对这些状态感兴趣,我会建议您将所有状态记录到javascript控制台以查看发生了什么.在加载大数据时,我也会给你tipp测试.很可能你会看到多个3 - 接收状态.


更新,也许我理解你的问题是错的(但不是你的代码;)..你在评论中告诉你,你看到两次准备就绪状态4.我在家测试了这个,并且100次警报对我来说很奇怪.

然后我将以下函数添加到您的javascript部分:

function alert(msg) {
    console.log(msg);
}
Run Code Online (Sandbox Code Playgroud)

这会将所有警报重定向到javascript调试控制台.我得到以下输出:

在此输入图像描述

我看到只有一次准备状态4.似乎你因为如此多的警报而自私了();)


Update2:正如我在评论中提到的那样@thanks Jeff-Meadows也指出了这一点:请注意,alert()除非你按下ok按钮,否则该函数将阻止javascript线程.由于异步XHR请求将由单独的浏览器线程处理,因此XHR将在警报消息上的javascript阻止时继续加载.您会发现这可能/会产生不必要的副作用,并使alert()不太适合进行调试.

  • 也许我误解了你 - 或者我误解了OP - 但听起来你只是描述了OP已经理解的行为.OP的问题是 - 如果我可以解释 - "为什么我的处理程序会被状态== 4"调用两次? (3认同)
  • 我不是天生的英语人士.我的意思是:那么多警报使得调试非常困难(对于人类而言).当然,警报对于调试控制台来说并不是那么好.请注意,警报将暂停javascript代码,除非您按下确定.这可能有**主要**副作用 (3认同)