/*
* 生成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();