天天看點

ajax 請求_【JavaScript 】Ajax網絡請求

ajax 請求_【JavaScript 】Ajax網絡請求

概述

什麼是AJAX?

  • AJAX = 異步 JavaScript 和 XML。
  • AJAX 是一種用于建立快速動态網頁的技術。
  • AJAX 不是新的程式設計語言,而是一種使用現有标準的新方法。 
  • AJAX 最大的優點是在不重新加載整個頁面的情況下,可以與伺服器交換資料并更新部分網頁内容。 
  • AJAX 不需要任何浏覽器插件,但需要使用者允許JavaScript在浏覽器上執行。

工作原理:

ajax 請求_【JavaScript 】Ajax網絡請求

AJAX是基于現有的Internet标準 

  • AJAX是基于現有的Internet标準,并且聯合使用它們:
  • XMLHttpRequest 對象 (異步的與伺服器交換資料) 
  • JavaScript/DOM (資訊顯示/互動)
  • CSS (給資料定義樣式) 
  • XML (作為轉換資料的格式)
  • AJAX應用程式與浏覽器和平台無關的!

建立 XMLHttpRequest 對象

文法:

variable=new XMLHttpRequest();
           

老舊版本:

variable=new ActiveXObject("Microsoft.XMLHTTP");
           

象伺服器發送請求

xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
           

說明:

open(method,url,async)
規定請求的類型、URL 以及是否異步處理請求。
    method:請求的類型;GET 或 POST
    url:檔案在伺服器上的位置
    async:true(異步)或 false(同步)

send(string)
将請求發送到伺服器,string:僅用于 POST 請求
           

GET 還是 POST?

與 POST 相比,GET 更簡單也更快,并且在大部分情況下都能用。然而,在以下情況中,請使用 POST 請求: 

  • 無法使用緩存檔案(更新伺服器上的檔案或資料庫) 
  • 向伺服器發送大量資料(POST 沒有資料量限制) 
  • 發送包含未知字元的使用者輸入時,POST 比 GET 更穩定也更可靠

示例:

//一個簡單的 GET 請求:
xmlhttp.open("GET","/ajax/demo_get",true);
xmlhttp.send();

//一個簡單 POST 請求:
xmlhttp.open("POST","/ajax/demo_post",true);
xmlhttp.send();
           

如果需要像 HTML 表單那樣 POST 資料,可以使用 setRequestHeader() 來添加 HTTP 頭。

然後在 send() 方法中發送資料:

xmlhttp.open("POST","/ajax/demo_post",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");
           

說明:

setRequestHeader(header,value)
向請求添加 HTTP 頭。
    header: 規定頭的名稱
    value: 規定頭的值
           

open() 方法的 url 參數也可以是伺服器上檔案的位址,該檔案可以是任何類型的檔案,比如 .txt 和 .xml,或者伺服器腳本檔案。

異步 - True 或 False?

AJAX 指的是異步 JavaScript 和 XML(Asynchronous JavaScript and XML)。 

XMLHttpRequest 對象如果要用于 AJAX 的話,其 open() 方法的 async 參數必須設定為 true:

xmlhttp.open("GET","ajax_test.html",true);
           

伺服器響應

獲得來自伺服器的響應,可使用 XMLHttpRequest 對象的 responseText 或 responseXML 屬性。

responseText   獲得字元串形式的響應資料。
responseXML 獲得XML形式的響應資料。
           

示例-文本json:

<html><head><meta charset="utf-8"><script>function loadXMLDoc(){var xmlhttp;if (window.XMLHttpRequest)
            {// IE7+, Firefox, Chrome, Opera, Safari 浏覽器執行代碼
                xmlhttp=new XMLHttpRequest();
            }else
            {// IE6, IE5 浏覽器執行代碼
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function(){if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
                }
            }
            xmlhttp.open("GET","http://wthrcdn.etouch.cn/weather_mini?citykey=101280101",true);
            xmlhttp.send();
        }script>head><body><div id="myDiv"><h2>使用 AJAX 修改該文本内容h2>div><button type="button" onclick="loadXMLDoc()">修改内容button>body>html>
           

運作,點選按鈕後效果:

ajax 請求_【JavaScript 】Ajax網絡請求

示例-XML對象進行解析:

<html><head><meta charset="utf-8"><script>function loadXMLDoc(){var xmlhttp;var txt,x,i;if (window.XMLHttpRequest)
  {// IE7+, Firefox, Chrome, Opera, Safari 浏覽器執行代碼
    xmlhttp=new XMLHttpRequest();
  }else
  {// IE6, IE5 浏覽器執行代碼
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  xmlhttp.onreadystatechange=function(){if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
      xmlDoc=xmlhttp.responseXML;
      txt="";
      x=xmlDoc.getElementsByTagName("ARTIST");for (i=0;i      {
        txt=txt + x[i].childNodes[0].nodeValue + "
";
      }document.getElementById("myDiv").innerHTML=txt;
    }
  }
  xmlhttp.open("GET","cd_catalog.xml",true);
  xmlhttp.send();
}script>head><body><h2>我收藏的 CD :h2><div id="myDiv">div><button type="button" onclick="loadXMLDoc()">擷取我的 CDbutton>body>html>
           

效果:

ajax 請求_【JavaScript 】Ajax網絡請求

onreadystatechange 事件

當請求被發送到伺服器時,我們需要執行一些基于響應的任務。每當 readyState 改變時,就會觸發 onreadystatechange 事件。readyState 屬性存有 XMLHttpRequest 的狀态資訊。

onreadystatechange   
存儲函數(或函數名),每當readyState 屬性改變時,就會調用該函數。

readyState 
存有 XMLHttpRequest 的狀态。從 0 到 4 發生變化。

    0: 請求未初始化
    1: 伺服器連接配接已建立
    2: 請求已接收
    3: 請求進行中
    4: 請求已完成,且響應已就緒

status 
200: "OK"
404: 未找到頁面
           

示例:

xmlhttp.onreadystatechange=function(){
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
      document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
           

使用回調函數

function myFunction(){
    loadXMLDoc("/ajax/ajax_info.txt",function(){
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
        }
    });
}
           

ajax.js網絡請求封裝示例

function ajax(url, fnSucc, fnFaild){
  //1.建立Ajax對象
  var oAjax=null;
  
  if(window.XMLHttpRequest)
  {
    oAjax=new XMLHttpRequest();
  }
  else
  {
    oAjax=new ActiveXObject("Microsoft.XMLHTTP");
  }
  
  //2.連接配接伺服器
  oAjax.open('GET', url, true);
  
  //3.發送請求
  oAjax.send();
  
  //4.接收伺服器的傳回
  oAjax.onreadystatechange=function (){
    if(oAjax.readyState==4) //完成
    {
      if(oAjax.status==200) //成功
      {
        fnSucc(oAjax.responseText);
      }
      else
      {
        if(fnFaild)
          fnFaild(oAjax.status);
      }
    }
  };
}
           

示例:

<html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>無标題文檔title><script src="ajax.js">script><script>window.onload=function (){var oBtn=document.getElementById('btn1');
  oBtn.onclick=function (){
    ajax('data.json', function (str){var arr=eval(str);
      alert(arr[0].b);
    });
  };
};script>head><body>
讀取伺服器上的一個檔案,檔案裡面放了一個json<br /><input id="btn1" type="button" value="讀取json" />body>html>
           

  碼上加油站

  一起來加油

長按掃碼關注

ajax 請求_【JavaScript 】Ajax網絡請求

點“在看”你懂得

ajax 請求_【JavaScript 】Ajax網絡請求

繼續閱讀