兼容ie7到ie11,chrome,firefox的ajax代码
Posted liuxuzzz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了兼容ie7到ie11,chrome,firefox的ajax代码相关的知识,希望对你有一定的参考价值。
/* * 生成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) { //return false; //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();
以上是关于兼容ie7到ie11,chrome,firefox的ajax代码的主要内容,如果未能解决你的问题,请参考以下文章
JQuery Autocomplete 与 IE7 的兼容性