AJAX筆記



AJAX===

一、ajax實現步驟:1、創建XMLHttpRequest對象
        2、設置回調函數
   xmlHttp.onreadystatechange = function() {
       if ( xmlHttp.readyState == 4 && xmlHttp.status == 200 ) {
       // 根據不同的返回類型處理響應
   }
        3、初始化XMLHttpRequest組件
   xmlHttp.open( type, url, async );

  get:xmlHttpRequest.open("GET",url,true);
  post:xmlHttpRequest.open("POST",url,true);
   xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        4、發送請求
   xmlHttp.send( null / string );

  get:xmlHttpRequest.send(null);
  post:xmlHttpRequest.send(數據信息);

二、XMLHttpRequest對象和ActiveX對象
 //  兼容寫法
 // 如果是 IE7+,FF 等高級瀏覽器
 if(window.XMLHttpRequest) {
 return new XMLHttpRequest();
 }
 // 如果是IE 5,IE6 低版本瀏覽器
 if( window.ActiveXObject) {
 return new ActiveXObject("Microsoft.XMLHTTP");
 }

三、XMLHttpRequest對象的屬性
 onreadystatechange  處理服務器響應的函數

 readyState     服務器響應的狀態信息:
    0請求未初始化
    1服務器連接已建成
    2請求已發送
    3請求處理中
    4請求已完成
 
 status      200:相應正確返回
       404:未找到頁面
 
 responseTest     獲取字符串形式的響應數據

 responseXML     獲取XML形式的相應數據

四、XMLHttpRequest對象的方法
 open(method,url,async)   創建http請求;
     method:請求的類型:GET或POST
     url:服務器請求地址
     async:是否異步請求,true(異步)或false(同步)

 send(string)   將請求發送到服務器
     注意:string僅用於post方法,get方法爲空或null
 
 setRequestHeader()       指定請求的某個HTTP頭

 getResposeHeader()  從響應中獲取指定的HTTP頭

五、文本和 XML方式響應的區別
 文本: var username = xmlHttpRequest.responseText;
  //省略其他代碼……
 
 XML:   var dom = xmlHttpRequest.responseXML;
  ......
  if(dom){
   var userNodes = dom.getElementsByTagName("username");
   if( userNodes.length > 0 ){
    var username= userNodes[0].firstChild.nodeValue;
    //省略其他代碼……
   }
  }

六、jQuery 實現 AJAX (簡化原生 JavaScript 實現 AJAX )
 $.ajax()方法

 $.ajax( {
  url : " 發送的請求地址",
  type : " 請求方式",
  data : " 要發送的數據",
  dataType : " 服務器返回的數據類型", // "xml html script json text"
  beforeSend : function(data) { // 碼 發送請求前執行的代碼 },
  success : function(data) { // 碼 發送成功後執行的代碼 },
  error : function() { // 碼 請求失敗執行的代碼 }
 } );

 
   $.get() 方法
是$.ajax()方法中類型爲GET請求的簡化版
 $.get() 方法
 $.get(
  " 發送的請求地址" ,
  要發送的數據 key/value ,
  回調函數 ,
  "返回內容格式,xml, html, script, json, text "
 );

 $.post() 方法
是$.ajax()方法中類型爲POST請求的簡化版
 $.post() 方法
 $.post(
  " 發送的請求地址" ,
  要發送的數據 key/value ,
  回調函數 ,
  " 返回內容格式,xml, html, script, json, text "
 );

 $.getJSON() 方法
是$.get()方法中返回數據類型爲JSON的簡化版
 $.getJSON() 方法
 $.getJSON(
  " 發送的請求地址" ,
  要發送的數據 key/value ,
  回調函數
 );

 $.getScript() 方法
通過 HTTP GET請求載入並執行一個JavaScript 文件
 $.getScript() 方法
 $. getScript(
  " 發送的請求地址" ,
  回調函數
 );

 serialize() 用於序列化表單內容爲字符串
 好處:不用逐個去獲取表單元素的值,拼湊參數序列
 serialize()
 $("form").serialize() ;
 // 返回參數序列
 single=Single&check=check2&radio=radio1


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章