1. 程式人生 > >AJAX之二 - XHR 請求

AJAX之二 - XHR 請求

目錄

向伺服器傳送請求

GET 還是 POST?

GET 請求

POST 請求

非同步 - True 或 False?

Async=true

Async = false


AJAX - 向伺服器傳送請求

當你的頁面全部載入完畢後,客戶端會通過 XMLHttpRequest 物件向伺服器請求資料,伺服器端接受資料並處理後,向客戶端反饋資料。


向伺服器傳送請求

將請求傳送到伺服器,我們使用 XMLHttpRequest 物件的 open() 和 send() 方法

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 請求

 

open方法和send方法解析:

1、傳送資料

(1)open方法繫結一個傳送過程,但不傳送資料。Send用於開始資料的傳送過程。

(2)open方法最後一個引數為true時表示非同步,否則表示同步。send方法可以傳入一個引數,在open方法的第一個引數為"POST"時有用,為post的資料,在"GET"時忽略該引數。

2、資料接收

(1)同步的時候,send方法要接收到伺服器返回的資料後才返回。

(2)在非同步的時候,send呼叫後立即返回,伺服器返回的資料在onreadystatechange設定的非同步回撥裡面進行讀取。

 


GET 還是 POST?

與 POST 相比,GET 更簡單也更快,並且在大部分情況下都能用。

然而,在以下情況中,請使用 POST 請求:

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

GET 請求

一個簡單的 GET 請求:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function loadXMLDoc()
{
var xmlhttp;
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","/statics/demosource/demo_get.php",true);
xmlhttp.send();
}
</script>
</head>
<body>

<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>

</body>
</html>

在上面的例子中,您可能得到的是快取的結果。

為了避免這種情況,請向 URL 新增一個唯一的 ID:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function loadXMLDoc()
{
var xmlhttp;
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","/statics/demosource/demo_get.php?t=" + Math.random(),true);
xmlhttp.send();
}
</script>
</head>
<body>

<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<p>Click the button several times to see if the time changes, or if the file is cached.</p>
<div id="myDiv"></div>

</body>
</html>

如果您希望通過 GET 方法傳送資訊,請向 URL 新增資訊:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function loadXMLDoc()
{
var xmlhttp;
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","/statics/demosource/demo_get2.php?fname=Henry&lname=Ford",true);
xmlhttp.send();
}
</script>
</head>
<body>

<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
 
</body>
</html>

提示:GET請求具有以下的幾個特點:

  • GET 請求可被快取
  • GET 請求保留在瀏覽器歷史記錄中
  • GET 請求可被收藏為書籤
  • GET 請求不應在處理敏感資料時使用
  • GET 請求有長度限制
  • GET 請求只應當用於取回資料


POST 請求

一個簡單 POST 請求:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function loadXMLDoc()
{
var xmlhttp;
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("POST","/statics/demosource/demo_post.php",true);
xmlhttp.send();
}
</script>
</head>
<body>

<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
 
</body>
</html>

如果需要像 HTML 表單那樣 POST 資料,請使用 setRequestHeader() 來新增 HTTP 頭。然後在 send() 方法中規定您希望傳送的資料:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function loadXMLDoc()
{
var xmlhttp;
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("POST","/statics/demosource/demo_post2.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");
}
</script>
</head>
<body>

<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
 
</body>
</html>
描述
setRequestHeader(header,value)

向請求新增 HTTP 頭。

  • header: 規定頭的名稱
  • value: 規定頭的值

 

提示:POST請求的特點如下:

  • POST 請求不會被快取
  • POST 請求不會保留在瀏覽器歷史記錄中
  • POST 請求不能被收藏為書籤
  • POST 請求對資料長度沒有要求

 



非同步 - True 或 False?

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

XMLHttpRequest 物件如果要用於 AJAX 的話,其 open() 方法的 async 引數必須設定為 true:

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

對於 web 開發人員來說,傳送非同步請求是一個巨大的進步。很多在伺服器執行的任務都相當費時。AJAX 出現之前,這可能會引起應用程式掛起或停止。

通過 AJAX,JavaScript 無需等待伺服器的響應,而是:

  • 在等待伺服器響應時執行其他指令碼
  • 當響應就緒後對響應進行處理

Async=true

當使用 async=true 時,請規定在響應處於 onreadystatechange 事件中的就緒狀態時執行的函式:

xmlhttp.onreadystatechange=function() 
  { 
  if (xmlhttp.readyState==4 && xmlhttp.status==200) 
    { 
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText; 
    } 
  } 
xmlhttp.open("GET","ajax_info.txt",true); 
xmlhttp.send();

具體的例子請看下面:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function loadXMLDoc()
{
var xmlhttp;
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","/statics/demosource/ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>

<div id="myDiv"><h2>使用 AJAX 修改該文字內容</h2></div>
<button type="button" onclick="loadXMLDoc()">修改內容</button>

</body>
</html>

Async = false

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

xmlhttp.open(引數1,引數2,false);

我們不推薦使用 async=false,但是對於一些小型的請求,也是可以的。

請記住,JavaScript 會等到伺服器響應就緒才繼續執行。如果伺服器繁忙或緩慢,應用程式會掛起或停止。

注意:當您使用 async=false 時,請不要編寫 onreadystatechange 函式 - 把程式碼放到 send() 語句後面即可:

xmlhttp.open("GET","ajax_info.txt",false); 
xmlhttp.send(); 
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

具體的例子可看下面例子:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.open("GET","/statics/demosource/ajax_info.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
</script>
</head>
<body>

<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>

 

 


注意:以上內容均為整理自W3School內容:https://www.w3cschool.cn/ajax/ajax-xmlhttprequest-send.html

此篇文章為自我學習筆記。