繁体   English   中英

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

[英]Why does the Ajax function I call in my script run twice in a row when readyState is 4?

所有,

我正在使用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']];}
?>

这是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']];
?>

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

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

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

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

function alert(msg) {
  console.log(msg);
}

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

解析度

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

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

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...

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

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);
}

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

在此输入图像描述

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


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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM