AJAX 简介

Ang AJAX ay pangarap ng mga developer, dahil makakaya ka ng:

  • Baguhin ang pahina ng walang pag-refresh
  • Hihilingin ang datos mula sa server pagkatapos ng pagkarga ng pahina
  • Tanggapin ang datos mula sa server pagkatapos ng pagkarga ng pahina
  • Magpadala ng datos sa server sa likod

AJAX 实例

Pindutin ang sumusunod na button upang magpalit ng teksto ng Ajax:

Subukan Nang Personal

Paliwanag ng Halimbawa ng AJAX

HTML Pahina

<!DOCTYPE html>
<html>
<body>
<div id="demo">
  <h2>Huwagang Magpalit ng Teksto ng AJAX</h2>
  <button type="button" onclick="loadDoc()">Baguhin ang Teksto</button>
</div>
</body>
</html> 

Ang HTML na pahina na ito ay naglalaman ng <div> at <button>.

<div> Para sa pagpapakita ng impormasyon mula sa server.

<button> Tawagan ang function (kapag ito ay pinindot).

Ang function na ito ay humihiling ng datos mula sa web server at ipapakita ito:

Function loadDoc()
function loadDoc() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
     document.getElementById("demo").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "ajax_info.txt", true);
  xhttp.send();
} 

Ano ang AJAX?

AJAX = Asynchronous JavaScript And XML.

AJAX is not a programming language.

AJAX simply combines:

  • Browser's built-in XMLHttpRequest object (requesting data from the web server)
  • JavaScript and HTML DOM (display or use data)

Ajax is a misleading name. Ajax applications may use XML to transmit data, but it is also common to transmit data as plain text or JSON text.

Ajax allows for asynchronous updating of web pages by exchanging data with the web server behind the scene. This means that only part of the web page can be updated without reloading the entire page.

How AJAX Works

AJAX
  1. An event occurs in the web page (page load, button click)
  2. Create the XMLHttpRequest object by JavaScript
  3. The XMLHttpRequest object sends a request to the web server
  4. The server processes the request
  5. The server sends the response back to the web page
  6. Read the response by JavaScript
  7. Perform the correct action by JavaScript (such as updating the page)