duancui19840401 2014-02-25 20:51
浏览 77

XJAX重用XMLHttp对象

So I've got a problem when trying to reuse an XMLHttp request object. I'm trying to incorporate AJAX into a site!

See my code below:

var XMLHttp = createXMLHttpRequestObject();
function createXMLHttpRequestObject() {
  var xmlHTTP;

  //First to deal with Internet Explorer >:(
  if (window.ActiveXObject){
    try {
      xmlHTTP = new ActiveXObject("Microsoft.XMLHTTP");
    } 
    catch (e) {
      xmlHTTP = false;
    }
  } else {
    try {
      xmlHTTP = new XMLHttpRequest();
    }
    catch (e) {
      xmlHTTP = false;
    }
  }

  if (!xmlHTTP)
    alert("Oops! Someone just unplugged the internet!");
  else
    return xmlHTTP;

}// XMLHttpRequest

function getAboutMe() {
  if (XMLHttp.readyState == 0 || XMLHttp.readyState == 4) {
    XMLHttp.open("GET", "http://repairiphonesuk.com/rachael/AJAX/getAboutMe.php", true);
    XMLHttp.onreadystatechange = handleServerResponse('AboutMe');
    XMLHttp.send();
  } else {
    setTimeout(getAboutMe(), 1000);
    alert("no");
  }
}

function getHome() {
  if (XMLHttp.readyState == 0 || XMLHttp.readyState == 4) {
    XMLHttp.open("GET", "http://repairiphonesuk.com/rachael/AJAX/getHome.php", true);
    XMLHttp.onreadystatechange = handleServerResponse('home');
    XMLHttp.send();
  } else {
    setTimeout(getHome(), 1000);
    alert("no");
  }
}


function handleServerResponse(from) {
  if (XMLHttp.readyState == 4 && XMLHttp.status == 200) {
    document.getElementById("displayContent").innerHTML = XMLHttp.responseText;
    if (from === 'home') {
      document.getElementById('displayContent').style.backgroundColor=transparent;
    }
  } else if (XMLHttp.status = 404) {
  }
}

When removing the getHome() function and the parameter to the handle request it works! Am I missing something obvious?

  • 写回答

1条回答 默认 最新

  • douchao1957 2014-02-25 21:04
    关注

    onreadystatechange takes a function assignment, what you're doing is calling a function and assigning the return to onreadystatechange. Correct this by wrapping your code in an anonymous function.

    XMLHttp.onreadystatechange = function (){handleServerResponse('home')};
    

    setTimeout takes a function as the first argument, what your doing is calling the function, basically the same thing with onreadystatechange, since getHome isn't taking any arguments just pass the function itself

    setTimeout(getHome, 1000);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在炒股软件中,爬到我想看的日k线
  • ¥15 51单片机中C语言怎么做到下面类似的功能的函数(相关搜索:c语言)
  • ¥15 seatunnel 怎么配置Elasticsearch
  • ¥15 PSCAD安装问题 ERROR: Visual Studio 2013, 2015, 2017 or 2019 is not found in the system.
  • ¥15 (标签-MATLAB|关键词-多址)
  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起