XML DOM 教學課程登入
XML DOM 教學課程
作者:php.cn  更新時間:2022-04-13 15:27:56

DOM XMLHttp請求


The XMLHttpRequest 物件


透過 XMLHttpRequest 對象,您可以在不重新載入整個頁面的情況下更新網頁中的某個部分。


XMLHttpRequest 物件

XMLHttpRequest 物件用於幕後與伺服器交換資料。

XMLHttpRequest 物件是開發者的夢想,因為您可以:

  • 在不重新載入頁面的情況下更新網頁

  • 在頁面已載入後從伺服器請求資料

  • 在頁面已載入後從伺服器接收資料

  • 在後台向伺服器發送資料


建立XMLHttpRequest 物件

所有現代的瀏覽器(IE7+、Firefox、Chrome、Safari 和Opera)都有一個內建置的XMLHttpRequest 物件。

建立XMLHttpRequest 物件的語法

xmlhttp=new XMLHttpRequest();

舊版的Internet Explorer(IE5 和IE6)使用ActiveX 物件:

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

為了處理所有現代的瀏覽器,包括IE5 和IE6,請檢查瀏覽器是否支援XMLHttpRequest對象。如果支持,則建立XMLHttpRequest 對象,如果不支持,則建立一個ActiveX 物件:

實例

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for 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","xmlhttp_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>

<h2>Using the XMLHttpRequest object</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>

執行實例»

點擊"運行實例" 按鈕查看線上實例



發送一個請求到伺服器

為了發送一個請求到伺服器,我們使用XMLHttpRequest 對象的open() 與send() 方法:

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

方法描述
#open(method,url,async) 規定請求的類型,URL,請求是否應該進行非同步處理。

method:請求的類型:GET 或POST
url:檔案在伺服器上的位置
async:true (非同步)或false(同步)
send(string)發送請求到伺服器。

string:僅用於 POST 請求


GET 或 POST?

GET 比 POST 簡單且快速,可用於大多數情況下。

然而,在下面的情況下請始終使用POST 請求:

  • #快取的檔案不是選項(更新伺服器上的檔案或資料庫)

  • 傳送到伺服器的資料量較大(POST 沒有大小的限制)

  • 發送使用者輸入(可以包含未知字元),POST 比GET 更強大更安全性


URL - 伺服器上的檔案

#open() 方法的url 參數,是伺服器上的檔案的位址:

xmlhttp.open("GET","xmlhttp_info.txt",true);

該檔案可以是任何類型的檔案(如.txt 和.xml),或伺服器腳本檔案(如.html 和.php,可在發送迴響應之前在伺服器上執行動作)。


非同步- True 或False?

如需非同步傳送請求,open() 方法的async 參數必要設定為true:

##xmlhttp. open("GET","xmlhttp_info.txt",true);
發送非同步請求對於Web 開發人員來說是一個巨大的進步。在伺服器上執行的許多任務非常費時。

透過非同步傳送,JavaScript 不需要等待伺服器的回應,但可以替換為:

  • 等待伺服器的回應時,執行其他腳本

  • 回應準備時處理回應


Async=true

當使用async=true 時,在onreadystatechange 事件中回應準備時規定一個要執行的函數:

實例

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for 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","xmlhttp_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>

<h2>Using the XMLHttpRequest object</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>

#運行實例»點擊"運行實例"按鈕查看線上實例



Async=false

如需使用async=false,請更改open() 方法的第三個參數為false:

xmlhttp.open("GET","xmlhttp_info.txt",false);
不建議使用async=false,但如果處理幾個小的請求還是可以的。

請記住,JavaScript 在伺服器回應準備之前不會繼續執行。如果伺服器正忙碌或緩慢,應用程式將掛起或停止。

注意:當您使用 async=false 時,不要寫 onreadystatechange 函數- 只要要把程式碼放置在send() 語句之後即可:

實例

#
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
xmlhttp=null;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
if (xmlhttp!=null)
  {
  xmlhttp.open("GET","xmlhttp_info.txt",false);
  xmlhttp.send();
  document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
  }
else
  {
  alert("Your browser does not support XMLHTTP.");
  }
}
</script>
</head>
<body>

<h2>Using the XMLHttpRequest object</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>
##執行實例»
點擊"運行實例" 按鈕查看線上實例

#


伺服器回應

如需從伺服器取得回應,請使用 XMLHttpRequest 物件的 responseText 或 responseXML 屬性。

屬性描述
#responseText取得回應資料作為字串
responseXML取得回應資料作為XML 資料


responseText 屬性

如果來自伺服器的回應不是XML,請使用responseText 屬性。

responseText 屬性以字串形式傳回回應,您可以相應地使用它:

#實例

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for 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","xmlhttp_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>

<h2>Using the XMLHttpRequest object</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>

運行實例»

點擊"運行實例" 按鈕查看線上實例



#responseXML 屬性

如果來自伺服器的回應不是XML,而您想要把它解析為XML 對象,請使用responseXML 屬性:

實例

請求檔 cd_catalog.xml 並解析回應:

#
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
xmlhttp=null;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
if (xmlhttp!=null)
  {
  xmlhttp.onreadystatechange=function()
    {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
      {
      xmlDoc=xmlhttp.responseXML;
      var txt="";
      x=xmlDoc.getElementsByTagName("ARTIST");
      for (i=0;i<x.length;i++)
        {
        txt=txt + x[i].childNodes[0].nodeValue + "<br>";
        }
      document.getElementById("myDiv").innerHTML=txt;
        }
      }
  xmlhttp.open("GET","cd_catalog.xml",true);
  xmlhttp.send();
  }
else
  {
  alert("Your browser does not support XMLHTTP.");
  }
}
</script>
</head>
<body>

<h2>My CD Collection:</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Get my CD collection</button>

</body>
</html>

#運行實例»

點擊"運行實例"按鈕查看線上實例



#onreadystatechange 事件

當請求被傳送到伺服器,我們要根據回應執行某些動作。

onreadystatechange 事件在每次 readyState 變更時被觸發。

readyState 屬性持有 XMLHttpRequest 的狀態。

XMLHttpRequest 物件的三個重要的屬性:

屬性描述
onreadystatechange儲存函數(或函數的名稱)在每次readyState 屬性變更時被自動呼叫
readyState存放了XMLHttpRequest 的狀態。從 0 到 4 變化:
0:請求未初始化
1:伺服器建立連線
2:收到的請求
3:處理請求
4:請求完成和回應準備就緒
status200:"OK"
404:找不到頁面

在 onreadystatechange 事件中,我們規定當伺服器的回應準備處理時會發生什麼。

當readyState 是4 或狀態是200 時,回應準備:

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for 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","xmlhttp_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>

<h2>Using the XMLHttpRequest object</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>

執行實例»

點擊"運行實例" 按鈕查看線上實例

注意:onreadystatechange 事件在每次readyState 發生變化時被觸發,總共觸發了四次。


tryitimg.gif更多實例


#透過getAllResponseHeaders() 檢索頭資訊
檢索資源(文件)的頭資訊。

實例

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc(url)
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById('p1').innerHTML=xmlhttp.getAllResponseHeaders();
    }
  }
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>
</head>
<body>

<p id="p1">The getAllResponseHeaders() function returns the header information of a resource, like length, server-type, content-type, last-modified, etc.</p>
<button onclick="loadXMLDoc('xmlhttp_info.txt')">Get header information</button>

</body>
</html>

運行實例»

點擊"運行實例" 按鈕查看線上實例


透過getResponseHeader() 檢索指定頭資訊
檢索資源(檔案)的指定頭資訊。

實例

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc(url)
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById('p1').innerHTML="Last modified: " + xmlhttp.getResponseHeader('Last-Modified');
    }
  }
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>
</head>
<body>

<p id="p1">The getResponseHeader() function is used to return specific header information from a resource, like length, server-type, content-type, last-modified, etc.</p>
<button onclick="loadXMLDoc('xmlhttp_info.txt')">Get "Last-Modified" information</button>

</body>
</html>

運行實例»

點擊"運行實例" 按鈕查看線上實例


檢索ASP 檔案的內容
當使用者在輸入欄位鍵入字元時,網頁如何與Web 伺服器進行通訊。

實例

<!DOCTYPE html>
<html>
<head>
<script>
function showHint(str)
{
if (str.length==0)
  { 
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<h3>Start typing a name in the input field below:</h3>
<form action=""> 
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p> 

</body>
</html>

運行實例»

點擊"運行實例" 按鈕查看線上實例


從資料庫中檢索內容
網頁如何透過XMLHttpRequest 物件從資料庫中提取資訊。

實例

<!DOCTYPE html>
<html>
<head>
<script>
function showCustomer(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }  
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getcustomer.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form action=""> 
<select name="customers" onchange="showCustomer(this.value)">
<option value="">Select a customer:</option>
<option value="ALFKI">Alfreds Futterkiste</option>
<option value="NORTS ">North/South</option>
<option value="WOLZA">Wolski Zajazd</option>
</select>
</form>
<br>
<div id="txtHint">Customer info will be listed here...</div>

</body>
</html>

運行實例»

點擊"運行實例" 按鈕查看線上實例


檢索XML 檔案的內容
建立一個XMLHttpRequest 從XML 檔案中檢索資料並把資料顯示在一個HTML 表格中。

實例

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc(url)
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    txt="<table border='1'><tr><th>Title</th><th>Artist</th></tr>";
    x=xmlhttp.responseXML.documentElement.getElementsByTagName("CD");
    for (i=0;i<x.length;i++)
      {
      txt=txt + "<tr>";
      xx=x[i].getElementsByTagName("TITLE");
        {
        try
          {
          txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
          }
        catch (er)
          {
          txt=txt + "<td> </td>";
          }
        }
      xx=x[i].getElementsByTagName("ARTIST");
        {
        try
          {
          txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
          }
        catch (er)
          {
          txt=txt + "<td> </td>";
          }
        }
      txt=txt + "</tr>";
      }
    txt=txt + "</table>";
    document.getElementById('txtCDInfo').innerHTML=txt;
    }
  }
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>
</head>
<body>

<div id="txtCDInfo">
<button onclick="loadXMLDoc('cd_catalog.xml')">Get CD info</button>
</div>

</body>
</html>

運行實例»

點擊"運行實例" 按鈕查看線上實例


#