AJAX 简介

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

  • I-update ang pahina ng walang pagrefresh
  • Humiling ng 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 实例

I-tap ang sumusunod na button upang palitan ang teksto ng Ajax:

Subukan Ng Iyong Sarili

Paliwanag Ng mga Halimbawa Ng AJAX

HTML Pahina

<!DOCTYPE html>
<html>
<body>
<div id="demo">
  <h2>Palitan ang 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 naititiklang).

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() {
    kung (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 JvaScript And XML.

AJAX is not a programming language.

AJAX simply combines:

  • Built-in XMLHttpRequest object in the browser (request 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 asynchronous updating of the web page by exchanging data with the Web server behind the scene. This means that 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 loading, 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)