码迷,mamicode.com
首页 > Web开发 > 详细

JS基础【原生JS实现的AJAX发送GET、POST】

时间:2015-06-02 15:38:33      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:

function AJAX() {
     var xhr = null;
     if(window.XMLHttpRequest) {
         xhr = new XMLHttpRequest();
     } else {
         try{
             xhr = new ActiveXObject(‘Microsoft.XMLHttp‘);
         }catch(e){
             xhr = new ActiveXObject(‘msxml2.xmlhttp‘);
         }
     }
     //get请求
     this.get = function(url,success,fail){
         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+")"));//【慎重使用eval】
                        } else if(ch=="["||ch=="{") {//json类型
                             txt = eval("("+txt+")");//【慎重使用eval】
                             success(txt);
                        } else {
                             success(txt);
                        }
                } else {
                     if(fail) {
                         fail(xhr.status);
                     }
                }
            } 
         };
         xhr.send(null);
     };
      
     //post请求
     this.post = function (url,param,success,fail) {
         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+")"));//【慎重使用eval】
                    } else if(ch=="["||ch=="{") {//json类型
                         txt = eval("("+txt+")");//【慎重使用eval】
                         success(txt);
                    } else {
                         success(txt);
                    }
                } else {
                     if(fail) {
                         fail(xhr.status);
                     }
                }
            }
         };
         xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
         xhr.send(param);
     };
}

*【注】:脚本中返回的数据结果,eval的使用需要慎重,在IE中可能会出现内存问题。


JS基础【原生JS实现的AJAX发送GET、POST】

标签:

原文地址:http://my.oschina.net/parker/blog/423807

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!