微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ajax工具方法

/*
 * 获取ajax对象
 */
function getXmlHttpRequest(){
    var xhr = null;
    if(typeof(XMLHttpRequest) != 'undefined'){
        xhr = new XMLHttpRequest();
    }else{
        xhr = new ActiveXObject("Microsoft.XMLHttp");
    }
    return xhr;
}

/*
 * post方式请求
 */
function post(url,queryString,fn){
    var xhr = getXmlHttpRequest();
    xhr.open('post',url,true);
    xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    xhr.onreadystatechange=function(){
        if(xhr.readyState == 4){
            if(xhr.status == 200){
                fn.apply(this,[xhr]);
            }
        }
    };
    xhr.send(queryString);
}

/*
 * get方式请求
 */
function get(url,fn){
    var xhr = getXmlHttpRequest();
    xhr.open('get',true);
    xhr.onreadystatechange=function(){
        if(xhr.readyState == 4){
            if(xhr.status == 200){
                fn.apply(this,[xhr]);
            }
        }
    };
    xhr.send(null);
}

 /*
  * 测试
  */
post("ajax","",function(xhr){
    alert(xhr.responseText);
});

From :http://www.w3school.com.cn/xmldom/dom_http.asp

原文地址:https://www.jb51.cc/ajax/166698.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐