Ajax交互的基本過(guò)程
當(dāng)前位置:點(diǎn)晴教程→知識(shí)管理交流
→『 技術(shù)文檔交流 』
交互的基本過(guò)程包括: l 創(chuàng)建XMLHttpRequest對(duì)象; l 發(fā)送請(qǐng)求; l 處理響應(yīng)。 創(chuàng)建XMLHttpRequest對(duì)象,不同的瀏覽器XMLHttpRequest對(duì)象的創(chuàng)建過(guò)程不太相同,需要針對(duì)不同的瀏覽器進(jìn)行不同的處理。下面的代碼展示了這個(gè)過(guò)程。讀者可以直接在自己的程序中使用下面的代碼。 var xMLHttpRequest=false; function createXMLHttpRequest(){ if(window.XMLRequest){ // Mozilla瀏覽器 xMLHttpRequest = new XMLHttpRequest(); }else if(window.ActiveObject){ try{ XMLHttpRequest = new ActiveXobject(“Msxml2.XMLHTTP”); }catch(e){ try{ XMLHttpRequest = new ActiveXobject(“Microsoft.XMLHTTP”); }catch(e){} } } } 對(duì)象創(chuàng)建之后是發(fā)送請(qǐng)求,首先通過(guò)open方法設(shè)置請(qǐng)求方式、請(qǐng)求的資源等,然后指定響應(yīng)方法,然后調(diào)用send方法發(fā)送。 function sendRequest(url){ createXMLHttpRequest(); XMLHttpRequest.open(“GET”,url,true); XMLHttpRequest.onreadystatechange=processResponse; //指定響應(yīng)函數(shù) XMLHttpRequest.send(null); //發(fā)送請(qǐng)求 } 客戶端接收到響應(yīng)信息之后,調(diào)用processResponse方法(在發(fā)送請(qǐng)求的時(shí)候設(shè)置的)進(jìn)行處理。 function processResponse(){ if(XMLHttpRequest.readystate==4){ // 判斷對(duì)象狀態(tài) if(XMLHttpRequest.status==200){ // 信息已經(jīng)返回,開始處理信息 var res = XMLHttpRequest.responseXML.getElementsByTagName(“res”)[0].firstChild.data; window.alert(res); }else{ // 頁(yè)面不正常 Window.alert(“您所請(qǐng)求的頁(yè)面有異常!”); } } } 該文章在 2010/8/18 14:26:09 編輯過(guò) |
相關(guān)文章
正在查詢... |