Ajax Not Working Right In Chrome/FireFox
This script I wrote works perfect on IE! It works on Chrome and FireFox the first time you do an action but it fails on the rest.
The script is simple. You can Add or Delete a user and each time you Add or Delete a user it updates the Updates the list.
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");
开发者_如何学Go } 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);
}
Please help and thank you
Use jQuery. You will have to write much less code and it will work in all browsers.
精彩评论