From 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:43:23 -0500 Subject: initial commit --- .../web/guide/ajax/getting_started/index.html | 287 +++++++++++++++++++++ files/zh-tw/web/guide/ajax/index.html | 119 +++++++++ 2 files changed, 406 insertions(+) create mode 100644 files/zh-tw/web/guide/ajax/getting_started/index.html create mode 100644 files/zh-tw/web/guide/ajax/index.html (limited to 'files/zh-tw/web/guide/ajax') diff --git a/files/zh-tw/web/guide/ajax/getting_started/index.html b/files/zh-tw/web/guide/ajax/getting_started/index.html new file mode 100644 index 0000000000..7e27c1ebac --- /dev/null +++ b/files/zh-tw/web/guide/ajax/getting_started/index.html @@ -0,0 +1,287 @@ +--- +title: 入門篇 +slug: Web/Guide/AJAX/Getting_Started +tags: + - AJAX + - API + - Advanced + - JavaScript + - WebMechanics + - XMLHttpRequest +translation_of: Web/Guide/AJAX/Getting_Started +--- +

這篇文章說明 AJAX 相關技術的基礎,並提供兩個簡單的實際操作範例供您入門。

+ +

AJAX 是什麼?

+ +

AJAX 代表 Asynchronous JavaScript And XML,即非同步 JavaScript 及 XML。簡單地說,AJAX 使用 {{domxref("XMLHttpRequest")}} 物件來與伺服器進行通訊。它可以傳送並接收多種格式的資訊,包括 JSON、XML、HTML、以及文字檔案。AJAX 最吸引人的特點是「非同步」的本質,這代表它可以與伺服溝通、交換資料、以及更新頁面,且無須重整網頁。

+ +

有兩項即將討論到的特點如下︰

+ + + +

第一步 – 如何發出 HTTP 請求

+ +

為了使用 JavaScript 向伺服器發送 HTTP 請求,便需要一個能夠提供相關功能的類別實體(an instance of a class)。這樣的類別最初由 Internet Explorer 以 ActiveX 物件的方式引入,稱為 XMLHTTP。Mozilla、Safari 及其他瀏覽器則隨後跟進,實作了 XMLHttpRequest 類別,以提供微軟最初的 ActiveX 物件中的方法及屬性。

+ +

因此,為了建立能夠跨瀏覽器的物件實體,可以這麼寫:

+ +
// Old compatibility code, no longer needed.
+if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...
+    httpRequest = new XMLHttpRequest();
+} else if (window.ActiveXObject) { // IE 6 and older
+    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
+}
+
+ +
備註:出於解說上的需要,上述代碼使用最簡方式建立 XMLHTTP 的實體。較貼近實際運用的範例,見第三步。
+ +

部分版本的 Mozilla 瀏覽器,在伺服器送回的資料未含 XML mime-type 標頭(header)時會出錯。為了避免這個問題,你可以用下列方法覆寫伺服器傳回的檔頭,以免傳回的不是 text/xml

+ +
httpRequest = new XMLHttpRequest();
+httpRequest.overrideMimeType('text/xml');
+
+ +

接下來是要決定伺服器傳回資料後的處理方式,此時你只要以 onreadystatechange 這個屬性指明要處理傳回值的 JavaScript 函式名稱即可,例如:

+ +
httpRequest.onreadystatechange = nameOfTheFunction;
+ +

注意,指定的函式名稱後不加括號也沒有參數。這只是簡單的賦值,而非真的呼叫函數。除了指定函式名稱外,你也能用 Javascript 即時定義函式的技巧(稱為〝匿名函數〞)來定一個新的處理函式,如下:

+ +
httpRequest.onreadystatechange = function(){
+    // 做些事
+};
+
+ +

決定處理方式之後你得確實發出 request,此時需叫用 HTTP request 類別的 open()send() 方法,如下:

+ +
httpRequest.open('GET', 'http://www.example.org/some.file', true);
+httpRequest.send();
+
+ + + +

send() 的參數在以 POST 發出 request 時,可以是任何想傳給伺服器的東西,而資料則以查詢字串的方式列出,例如:

+ +
"name=value&anothername="+encodeURIComponent(myVar)+"&so=on"
+ +

不過如果你想要以 POST 方式傳送資料,則必須先將 MIME 型態改好,如下:

+ +
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
+
+ +

否則伺服器就不會理你傳過來的資料了。

+ +

第二步 – 處理伺服器傳回的資料

+ +

傳出 request 時必須提供處理傳回值的函數名稱,這個函數是用來處理伺服器的回應。

+ +
httpRequest.onreadystatechange = nameOfTheFunction;
+
+ +

那麼來看看這個函數該做些什麼。首先,它必須檢查 request 目前的狀態。如果狀態值為 4 代表伺服器已經傳回所有資訊了,便可以開始解析所得資訊。

+ +
if (httpRequest.readyState === XMLHttpRequest.DONE) {
+    // 一切 ok, 繼續解析
+} else {
+    // 還沒完成
+}
+
+ +

readyState 所有可能的值如下:

+ + + +

資料來源:MSDN

+ +

接下來要檢查伺服器傳回的 HTTP 狀態碼。所有狀態碼列表可於 W3C 網站上查到,但我們要管的是 200 OK 這種狀態。

+ +
if (httpRequest.status === 200) {
+    // 萬事具備
+} else {
+    // 似乎有點問題。
+    // 或許伺服器傳回了 404(查無此頁)
+    // 或者 500(內部錯誤)什麼的。
+}
+
+ +

檢查傳回的 HTTP 狀態碼後,要怎麼處理傳回的資料就由你決定了。有兩種存取資料的方式:

+ + + +

第三步 – 簡單範例

+ +

好,接著就做一次簡單的 HTTP 範例,演示方才的各項技巧。這段 JavaScript 會向伺服器要一份裡頭有「I'm a test.」字樣的 HTML 文件(test.html),而後以 alert() 將文件內容列出。

+ +
<button id="ajaxButton" type="button">Make a request</button>
+
+<script>
+(function() {
+  var httpRequest;
+  document.getElementById("ajaxButton").addEventListener('click', makeRequest);
+
+  function makeRequest() {
+    httpRequest = new XMLHttpRequest();
+
+    if (!httpRequest) {
+      alert('Giving up :( Cannot create an XMLHTTP instance');
+      return false;
+    }
+    httpRequest.onreadystatechange = alertContents;
+    httpRequest.open('GET', 'test.html');
+    httpRequest.send();
+  }
+
+  function alertContents() {
+    if (httpRequest.readyState === XMLHttpRequest.DONE) {
+      if (httpRequest.status === 200) {
+        alert(httpRequest.responseText);
+      } else {
+        alert('There was a problem with the request.');
+      }
+    }
+  }
+})();
+</script>
+
+ +

在此範例中:

+ + + +

你可以由此測試本例,也可以參考測試檔案

+ +
Note:如果你傳送一個要求到一段代碼,而這段代碼將回應XML而非靜態的HTML檔,那則必須要設定一個可以在IE中運作的header。如果我們不設定header  Content-Type: application/xml,IE將會在我們試圖運作的XML項目行下,回應一個"Object Expected" 的錯誤。
+ +
Note 2: 如果我們沒有設定header Cache-Control: no-cache,那瀏覽器將會藏匿response並且不再重新傳送request,造成除錯上的挑戰。我們也可以增加一個 always-different GET 參數,像是 timestamp 或 random number (詳見bypassing the cache)
+ +
Note 3: If the httpRequest variable is used globally, competing functions calling makeRequest() can overwrite each other, causing a race condition. Declaring the httpRequest variable local to a closure containing the AJAX functions avoids this.
+ +

In the event of a communication error (such as the server going down), an exception will be thrown in the onreadystatechange method when accessing the response status. To mitigate this problem, you could wrap your if...then statement in a try...catch:

+ +
function alertContents() {
+  try {
+    if (httpRequest.readyState === XMLHttpRequest.DONE) {
+      if (httpRequest.status === 200) {
+        alert(httpRequest.responseText);
+      } else {
+        alert('There was a problem with the request.');
+      }
+    }
+  }
+  catch( e ) {
+    alert('Caught Exception: ' + e.description);
+  }
+}
+
+ +

第四步 – 運用 XML 資料

+ +

前面的例子中,在收到 HTTP 傳回值後我們以物件的 reponseText 屬性接收 test.html 檔案的內容,接著來試試 responseXML 屬性。

+ +

首先,我們得做個格式正確的 XML 文件以便稍後取用。文件 (test.xml) 內容如下:

+ +
<?xml version="1.0" ?>
+<root>
+    I'm a test.
+</root>
+
+ +

在程式中,我們叫用檔案的地方只須略事修改如下:

+ +
...
+onclick="makeRequest('test.xml')">
+...
+
+ +

接著在 alertContents() 中,我們把 alert(http_request.responseText); 改成這樣:

+ +
var xmldoc = httpRequest.responseXML;
+var root_node = xmldoc.getElementsByTagName('root').item(0);
+alert(root_node.firstChild.data);
+
+ +

這樣一來我們便可取得 responseXML 所傳回的 XMLDocument 物件,而後以 DOM 方法取用 XML 文件的內容。你可以參考 test.xml 的原始碼 以及修改過後的測試程式

+ +

關於 DOM 方法,請參考 Mozilla DOM 文件。

+ +

Step 5 – Working with data

+ +

Finally, let's send some data to the server and receive a response. Our JavaScript will request a dynamic page this time, test.php, which will take the data we send and return a "computed" string - "Hello, [user data]!" - which we'll alert().

+ +

First we'll add a text box to our HTML so the user can enter their name:

+ +
<label>Your name:
+  <input type="text" id="ajaxTextbox" />
+</label>
+<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
+  Make a request
+</span>
+ +

We'll also add a line to our event handler to get the user's data from the text box and send it to the makeRequest() function along with the URL of our server-side script:

+ +
  document.getElementById("ajaxButton").onclick = function() {
+      var userName = document.getElementById("ajaxTextbox").value;
+      makeRequest('test.php',userName);
+  };
+
+ +

We need to modify makeRequest() to accept the user data and pass it along to the server. We'll change the request method from GET to POST, and include our data as a parameter in the call to httpRequest.send():

+ +
  function makeRequest(url, userName) {
+
+    ...
+
+    httpRequest.onreadystatechange = alertContents;
+    httpRequest.open('POST', url);
+    httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
+    httpRequest.send('userName=' + encodeURIComponent(userName));
+  }
+
+ +

The function alertContents() can be written the same way it was in Step 3 to alert our computed string, if that's all the server returns. However, let's say the server is going to return both the computed string and the original user data. So if our user typed "Jane" in the text box, the server's response would look like this:

+ +

{"userData":"Jane","computedString":"Hi, Jane!"}

+ +

To use this data within alertContents(), we can't just alert the responseText, we have to parse it and alert computedString, the property we want:

+ +
function alertContents() {
+  if (httpRequest.readyState === XMLHttpRequest.DONE) {
+    if (httpRequest.status === 200) {
+      var response = JSON.parse(httpRequest.responseText);
+      alert(response.computedString);
+    } else {
+      alert('There was a problem with the request.');
+    }
+  }
+}
+ +

The test.php file should contain the following:

+ +
$name = (isset($_POST['userName'])) ? $_POST['userName'] : 'no name';
+$computedString = "Hi, " . $name;
+$array = ['userName' => $name, 'computedString' => $computedString];
+echo json_encode($array);
+ +

For more on DOM methods, be sure to check Mozilla's DOM implementation documents.

diff --git a/files/zh-tw/web/guide/ajax/index.html b/files/zh-tw/web/guide/ajax/index.html new file mode 100644 index 0000000000..8e6a49698f --- /dev/null +++ b/files/zh-tw/web/guide/ajax/index.html @@ -0,0 +1,119 @@ +--- +title: Ajax +slug: Web/Guide/AJAX +translation_of: Web/Guide/AJAX +--- +
入門篇
+Ajax 簡介。
+ +
+

非同步 JavaScript 及 XML(Asynchronous JavaScript and XML,AJAX) 並不能稱做是種「技術」,而是 2005 年時由 Jesse James Garrett 所發明的術語,描述一種使用數個既有技術的「新」方法。這些技術包括 HTMLXHTML層疊樣式表JavaScript文件物件模型XMLXSLT 以及最重要的 XMLHttpRequest 物件
+ 當這些技術被結合在 Ajax 模型中,Web 應用程式便能快速、即時更動介面及內容,不需要重新讀取整個網頁,讓程式更快回應使用者的操作。

+ +

雖然 X 在 Ajax 中代表 XML,但由於 JSON 的許多優點,如輕量以及其本身就是 JavaScript 的一部分等,讓現今 JSON 比起 XML 被更廣泛的使用。JSON 與 XML 兩者都被用來在 Ajax 模型中包裝資訊。

+
+ +
+
+

文件

+ +
+
入門篇
+
這篇文章會指引你瞭解 Ajax 的基礎知識並提供了兩個簡單的動手做範例來入門。
+
使用 XMLHttpRequest API
+
XMLHttpRequest API 是 Ajax 的核心。這篇文章將解釋如何使用一些 Ajax 技術,例如: + +
+
Fetch API
+
Fetch API 提供了取得資源(fetching resources)的介面(interface)。這似乎對於曾使用過 {{domxref("XMLHTTPRequest")}} 的人而言並不陌生,然而這個 API 提供一個更強大且彈性的功能集。
+
Server-sent events
+
傳統上來說,一個網頁必須送出 request 到伺服器來得到新的資料,也就是說,網頁藉由server-sent 事件從伺服器請求 (request) 資料,伺服器在任何時候都能送新的資料給網頁,藉由推送訊息到網頁。這些傳入的訊息可以被視為網頁中的 事件 + 資料,請參見 使用server-sent event 
+
Pure-Ajax navigation example
+
This article provides a working (minimalist) example of a pure-Ajax website composed only of three pages.
+
Sending and Receiving Binary Data
+
The responseType property of the XMLHttpRequest object can be set to change the expected response type from the server. Possible values are the empty string (default), "arraybuffer", "blob", "document", "json", and "text". The response property will contain the entity body according to responseType, as an ArrayBuffer, Blob, Document, JSON, or string. This article will show some Ajax I/O techniques.
+
XML
+
可擴展標記語言(The Extensible Markup Language, XML)是W3C推薦的用於創建特殊用途標記語言的通用標記語言。它是SGML的簡化子集,能夠描述許多不同類型的數據。其主要目的是促進不同系統間的數據共享,特別是通過網際網路連接的系統。
+
JXON
+
JXON 代表無損耗 Javascript XML Object Notation, 是一個通用名稱,用來定義使用 XML 的 Javascript 物件樹(JSON) 的通用名稱。
+
解析和序列化 XML
+
如何從一串字串,一個檔案中透過 Javascript 解析一個 XML 文件  ,以及如何將 XML 檔案序列化成字串、Javascript 物件樹(JXON) 或檔案。 
+
XPath
+
XPath stands for XML Path Language, it uses a non-XML syntax that provides a flexible way of addressing (pointing to) different parts of an XML document. As well as this, it can also be used to test addressed nodes within a document to determine whether they match a pattern or not.
+
The FileReader API
+
The FileReader API lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read. File objects may be obtained from a FileList object returned as a result of a user selecting files using the <input> element, from a drag and drop operation's DataTransfer object, or from the mozGetAsFile() API on an HTMLCanvasElement.
+
HTML in XMLHttpRequest
+
The W3C XMLHttpRequest specification adds HTML parsing support to XMLHttpRequest, which originally supported only XML parsing. This feature allows Web apps to obtain an HTML resource as a parsed DOM using XMLHttpRequest.
+
Other resources
+
Other Ajax resources you may find useful.
+
+ +

View All...

+ +

參見

+ +
+
Alternate Ajax Techniques
+
Most articles on Ajax have focused on using XMLHttp as the means to achieving such communication, but Ajax techniques are not limited to just XMLHttp. There are several other methods.
+
Ajax: A New Approach to Web Applications
+
Jesse James Garrett, of adaptive path, wrote this article in February 2005, introducing Ajax and its related concepts.
+
A Simpler Ajax Path
+
"As it turns out, it's pretty easy to take advantage of the XMLHttpRequest object to make a web app act more like a desktop app while still using traditional tools like web forms for collecting user input."
+
Ajax Mistakes
+
Alex Bosworth has written this article outlining some of the mistakes Ajax application developers can make.
+
Tutorial with examples.
+
 
+
XMLHttpRequest specification
+
W3C Working draft
+
+
+ + +
+ +

{{ListSubpages}}

-- cgit v1.2.3-54-g00ecf