兼容ie7到ie11,edge,chrome,firefox的ajax发送接收post数据代码

/*
 * 生成XMLHttpRequest
 */
function getxhr()
{
    //获取ajax对象
    var xhr = null;
    try
    {
        xhr = new XDomainRequest();
    }
    catch(e)
    {
        try
        {
            xhr = new XMLHttpRequest();
        }
        catch(e)
        {
            try
            {
                xhr = new ActiveXObject("Msxml2.XMLHTTP");
            }
            catch(e)
            {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
        }
    }
    return xhr;
}

/*
 * 获取cookieName值
 */
function getCookie(cookieName)
{
    var cookieArr = document.cookie.split("; ");
    var length  = cookieArr.length;
    for(var i=0;i<length;i++)
    {
        var tmpArr = cookieArr[i].split("=");
        if(tmpArr[0]==cookieName)
        {
            return tmpArr[1];
        }
    }
    return '';
}

/*
 * 拼装cookie POST数据
 */
function getCookieData()
{
    var sessionid = getCookie('PHPSESSID');
var user_name= getCookie('user_name');
if(sessionid == '' || user_name == '') { return false; } var postData = { 'sessionid':sessionid, 'user_name':user_name }; return postData; } /* * ajax通信 */ function submitCookieTopForm() { var xhr = getxhr(); if (!xhr) { alert("您的浏览器不支持AJAX!"); return false; } //设置ajax数据 var url = "http://你的url"; //set post var formData = getCookieData(); if (false == formData) { return false; } var postData = JSON.stringify(formData); //开始ajax /********ie 8,9兼容***********/ try { if( xhr instanceof XDomainRequest) { xhr.open("post",url); xhr.timeout = 10000; xhr.onprogress = function() { }; xhr.onerror = function () { }; xhr.ontimeout = function () {}; xhr.onload = function() { try { var response = JSON.parse(xhr.responseText); //返回成功 } catch (e) { return false; //alert("服务器出错"); } } xhr.send(postData); return false; } } catch(e) { //pass } /********ie 8,9兼容结束***********/ xhr.open("POST",url,true); xhr.setRequestHeader("Content-Type","application/json;charset=utf-8"); xhr.open("POST",url,true); xhr.setRequestHeader("Content-Type","application/json;charset=utf-8"); xhr.onreadystatechange = function(){ if (xhr.readyState == 4) { if (xhr.status == 200) { //显示错误信息 try { var response = JSON.parse(xhr.responseText); //返回成功 } catch (e) { //alert("服务器出错"); } } else { //alert("网络错误"); } } } xhr.send(postData); return false; } submitCookieTopForm();

 

posted @ 2016-06-21 19:07  liuxuzzz  阅读(3193)  评论(0编辑  收藏  举报