Ajax的小封装get,post请求
时间:2021-07-01 10:21:17
帮助过:19人阅读
Ajax的小封装对ajax的get请求的小封装
- function Ajax() {
- var xhr =null;
- if(window.XMLHttpRequest) {
- xhr = new XMLHttpRequest();
- } else {
-
- xhr = new ActiveXObject("Microsoft.XMLHttp");
- }
- this.get=function(url,success,fail){ //get请求
- xhr.open("GET", "1.jsp",true);
- xhr.onreadystatechange=function(){
- if(xhr.readyState==4) {
- alert(xhr.status);
- if(xhr.status==200) {
- var txt = xhr.responseText;
- txt = eval("("+txt+")");
- var ch = txt.charAt(0);
- if(ch=="<") { //xml类型
- var xml = xhr.responseXML;
- success(eval("("+xml+")"));
- } else if(ch=="["||ch=="{") {//json类型
- txt = eval("("+txt+")");
- success(txt);
- } else {//不知道直接返回
-
- success(txt);
- }
- } else {
- if(fail) {
- fail(xhr.status);
- }
- }
- }
-
- };
- xhr.send(null);
-
- };
-
-
- this.post = function (url,param,success,fail) {//post请求
- xhr.open("POST", "1.jsp",true);
- xhr.onreadystatechange=function(){
- if(xhr.readyState==4) {
- alert(xhr.status);
- if(xhr.status==200) {
- var txt = xhr.responseText;
- var ch = txt.charAt(0);
- if(ch=="<") { //xml类型
- var xml = xhr.responseXML;
- success(eval("("+xml+")"));
- } else if(ch=="["||ch=="{") {//json类型
- txt = eval("("+txt+")");
- success(txt);
- } else {//不知道直接返回
-
- success(txt);
- }
-
- } else {
- if(fail) {
- fail(xhr.status);
- }
- }
- }
-
- };
- xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
- xhr.send(param);
- };
-
- }
|