Ajax在Chrome / FireFox中无法正常工作

时间:2010-09-30 07:48:39

标签: javascript ajax

我写的这个脚本在IE上完美运作!它可以在您第一次执行操作时在Chrome和FireFox上运行,但在其余部分时会失败。

脚本很简单。您可以添加或删除用户,每次添加或删除用户时,都会更新“更新”列表。

function Add() {
  http_request = false;
  cache=Math.random();
  var username=document.getElementById('username').value;
  if (window.XMLHttpRequest) { // Mozilla, Safari,...
      http_request = new XMLHttpRequest();
      if (http_request.overrideMimeType) {
        http_request.overrideMimeType('text/html');
      }
  } else if (window.ActiveXObject) { // IE
      try {
        http_request = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
        try {
            http_request = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {}
      }
  }
  if (!http_request) {
      return false;
  }
  http_request.onreadystatechange=function(){ if (http_request.readyState==4 && http_request.status==200){ if (http_request.responseText=="OK"){ Update(); } else { document.getElementById('Response').innerHTML=http_request.responseText; } } }
  http_request.open('POST', 'add.php?username='+username+'&cache='+cache, true);
  http_request.send(null);
}

function Delete(username) {
  http_request = false;
  if (window.XMLHttpRequest) { // Mozilla, Safari,...
      http_request = new XMLHttpRequest();
      if (http_request.overrideMimeType) {
        http_request.overrideMimeType('text/html');
      }
  } else if (window.ActiveXObject) { // IE
      try {
        http_request = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
        try {
            http_request = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {}
      }
  }
  if (!http_request) {
      return false;
  }
  http_request.onreadystatechange=function(){ if (http_request.readyState==4 && http_request.status==200){ Update(); } }
  http_request.open('POST', 'delete.php?username='+username, true);
  http_request.send(null);
}

function Update() {
  http_request = false;
  if (window.XMLHttpRequest) { // Mozilla, Safari,...
      http_request = new XMLHttpRequest();
      if (http_request.overrideMimeType) {
        http_request.overrideMimeType('text/html');
      }
  } else if (window.ActiveXObject) { // IE
      try {
        http_request = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
        try {
            http_request = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {}
      }
  }
  if (!http_request) {
      return false;
  }
  http_request.onreadystatechange=function(){ if (http_request.readyState==4 && http_request.status==200){ document.getElementById("list").innerHTML=http_request.responseText; } }
  http_request.open('GET', 'list.php', true);
  http_request.send(null);
}

请帮助并谢谢

1 个答案:

答案 0 :(得分:0)

使用jQuery。您必须编写更多更少的代码,它将适用于所有浏览器。