1. 程式人生 > >Ajax,純Js+Jquery

Ajax,純Js+Jquery

刷新 app 部分 span -- esp ont ica 接受

AJAX:Asynchronous Javascript and xml 異步,Js和Xml 交互式網頁開發 不刷新頁面,與服務器交互 詳情請參照Jquery工具指南
用在瀏覽器端的技術,無刷新,通過XmlHttpRequest訪問頁面
純js版----------

if(XmlHttpRequest){ //判斷是否支持XmlHttpRequest
xhr= new XmlHttpRequest(); // 創建XmlHttpRequest對象
}
else{
xhr= new Activexobject("Microsoft.XMLHTTP"); //不支持XmlHttpRequest,使用此方法創建
}
xhr.open("get|post","url",true);
xhr.send(); // 開始發送
xhr.onreadystatechange= function(){ // 回調函數,當服務器將數據返回給瀏覽器觸發方法
if(xhr.readyState==4) //0沒調用open方法,1表示未調用send方法,2正在等待狀態碼和頭的返回,3 已接受部分數據,但還沒接受完,不能使用該對象的屬性和方法,4已加載,所有數據執行完畢
if(xhr.status==200){ // 響應狀態碼,表示頁面執行無誤
alert(xhr.responseText); // 輸出接受到的文本
}
}

  


在send中寫數據。並添加請求報頭

xhr.setRequestHeader("Content-Type",application/x-www-form-urlencoded)
xhr.send("id=123&pwd=456");

-------------------------------------
Jquery版
強大的Jquery。。只需要get頁面就夠了

$.get("url",{"id" : "123","pwd":456},function(data)){ //自動把參數當做get請求傳輸
alert(data)
}

只需要post頁面。

$.post("url",{"id" : 123,"pwd":456},function
(data)){ //post請求 alert(data) }

//第三種寫法

$.ajax({
type="get"| post,
url="...",
data:"參數",
success:function(msg){...} // msg為從服務器接受到的數據
})

Ajax,純Js+Jquery