AJAX應用的五個步驟

1.創建xmlHttpRequest對象ajax

    if(window.XMLHttpRequest) {
    xmlHttp = new XMLHttpRequest();
    if(xmlHttp.overrideMimeType) {
     xmlHttp.overrideMimeType("text/xml");
    }
   } else if(window.ActiveXobject) {
    var activeName = ["MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
    for(var i = 0; i < activeName.length; i++) {
     try {
      xmlHttp = new ActiveXobject(activeName[i]);
      break;
     } catch(e) {}
    }
   }
   if(!xmlHttp) {
    alert("建立xmlhttprequest對象失敗");
   } else {}服務器

2.設置回調函數app

   xmlHttp.onreadystatechange= callback;ide

   function callback(){}函數

3.使用OPEN方法與服務器創建鏈接  xmlHttp.open("get","ajax?name="+ name,true)post

   此步注意設置http的請求方式(post/get),若是是POST方式,注意設置請求頭信息xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded")url

4.向服務器端發送數據code

  xmlHttp.send(null);orm

  若是是POST方式就不爲空xml

5.在回調函數中針對不一樣的響應狀態進行處理

  if(xmlHttp.readyState == 4){       //判斷交互是否成功

      if(xmlHttp.status == 200){         //獲取服務器返回的數據         //獲取純文本數據

        var responseText =xmlHttp.responseText;

       document.getElementById("info").innerHTML = responseText;

      }

   }

相關文章
相關標籤/搜索