1. 獲取瀏覽器的XMLHttpRequest對象,獲取的方式有如下幾種
1.1
function getXMLHttpRequest()
{
var xmlhttpReq = null;
if(window.ActiveXObject) //IE瀏覽器
{
xmlhttpReq = new ActiveXObject("MSXML2.XMLHTTP.3.0");
}else if(window.XMLHttpRequest) //其他瀏覽器
{
xmlhttpReq = new XMLHttpRequest();
}
return xmlhttpReq;
}
1.2
function getXMLHttpRequest() {
var xmlHttpReq=null;
if (window.XMLHttpRequest) {//Mozilla 瀏覽器
xmlHttpReq = new XMLHttpRequest();
}else {
if (window.ActiveXObject) {//IE 瀏覽器
try {
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
try {//IE 瀏覽器
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
}
}
}
}
return xmlHttpReq;
}
1.3
function ajaxFunction(){
var xmlHttp;
try{ // Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e){
try{// Internet Explorer
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){}
}
}
return xmlHttp;
}
2. 使用Ajax技術向服務器發出請求
function requestMeg(url,select)
{
//1. 獲取XMLHttpReques對象
var xmlReq = getXMLHttpRequest();
//2. 註冊監聽器
xmlReq.onreadystatechange = function()
{
//狀態碼
/*
0 -未初始化還沒有使用send方法向服務器發送數據
1- 載入,已經向服務器發出了請求但還沒有相應
2- send方法執行完成。已經接收到全部相應內容
3- 正在解析相應內容
4- 相應解析完成,數據可以使用
*/
if(xmlReq.readyState == 4)
{
//如果服務器返回的是xml文檔的話就使用responseXML來獲取服務器端的數據
var msg = xmlReq.responseXML;
//如果是html文件的數據則中responseText來獲取數據
var msg = xmlReq.responseText;
//如果接受到的是json格式的數據需要使用eval函數來轉換
var msg = xmlReq.responseText;
var json = eval("(" +msg+ ")");
//注意向服務器發送中文數據時需要進行url編碼,例如:encodeURI("中文");
}
};
//3. 準備發送數據
xmlReq.open("GET",url,true);
//4. 發送數據,注意如果是GET請求的話只能在請求的url地址後面跟數據
//如果是POST請求的話就可以在send函數中儲存要發送的數據了
xmlReq.send(null);
}
js中的總結
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.