AJAX原生JS代码

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了AJAX原生JS代码相关的知识,希望对你有一定的参考价值。

var http_request = false;
function send_request(method,url,content,responseType,callback){
http_request = false;
if(window.XMLHttpRequest) { //现代浏览器
http_request = new XMLHttpRequest();
if(http_request.overrideMimeType) {
http_request.overrideMimeType("text/xml");
}
} 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) {
window.alert("Can‘t create XMLHttpRequest");
return false;
}
if(responseType.toLowerCase() == "text") {
//http_request.onreadystatechange = processTextResponse;
http_request.onreadystatechange = callback;
} else if(responseType.toLowerCase == "xml") {
//http_request.onreadystatechange = processXMLResponse;
http_request.onreadystatechange = callback;
} else {
window.alert("error");
return false;
}

if(method.toLowerCase() == "get") {
http_request.open(method, url, true);
} else if(method.toLowerCase() == "post") {
http_request.open(method, url, true);
http_request.setRequestHeader("content-Type","application/x-www-form-urlencoded");
} else {
window.alert("http request error");
return false;
}
http_request.send(content);
}

function processTextResponse() {
if(http_request.readyState == 4) {
if(http_request.status == 200) {
alert(http_request.responseText);
} else {
alert("request error");
}
}
}

function processXMLResponse() {
if(http_request.readyState == 4) {
if(http_request.status == 200) {
alert(http_request.responseXML);
} else {
alert("request error");
}
}
}

以上是关于AJAX原生JS代码的主要内容,如果未能解决你的问题,请参考以下文章

原生js封装ajax代码

Ajax (Asynchronous javascript xml) 搜索框核心代码(JQuery) Ajax判断用户名存在核心代码 附:原生js的Ajax代码

原生JS写的ajax函数

JS原生Ajax

原生js 封装ajax请求超详细

原生js写ajax请求(复习)