Ajax Guide

AJAX works

A, Ajax technology included

Ajax is not a new technology, but rather a combination of existing technologies. It is made by a combination of these techniques.

  1. CSS and XHTML to represent.
  2. Use DOM dynamic display and interaction models.
  3. Asynchronous communication using XMLHttpRequest and a server.
  4. Use Javascript to bind and calls.

Second, how to create Ajax

The principle is simple Ajax XmlHttpRequest object to send to the server through the asynchronous request, obtain data from the server, and then manipulating the DOM Javascript page update. This is among the most crucial step is to obtain the requested data from the server.

Native to create Ajax can be divided into the following four steps:

1, create XMLHttpRequest object

All modern browsers have built-in XMLHttprequest object. If supported, XMLHttpRequest objects are created. If not, create ActiveObject:

var xhr = new XMLHttpRequest();

Old versions of IE (5 and 6) using ActiveX objects;

var xhr = new ActiveXobject("Microsoft.XMLHTTP");

In order to cope with all modern browsers, use the following code,

var xhr;
if (XMLHttpRequest){
    xhr = new XMLHttpRequest();
}else{
    xhr = new ActiveXObject("Microsoft.XMLHTTP");
}

2 Prepare the request

Initialize the XMLHttpRequest object, accepts three parameters:

xhr.open(method,url,async);

The first parameter indicates the type of the query string, whose value may be GET or POST. GET request:

xhr.open("GET",demo.php?name=tsrot&age=24,true);

POST request:

xhr.open("POST",demo.php,true);

The second parameter is sent to a destination URL request. The third parameter is true or false, indicating that the request is an asynchronous or synchronous mode emitted.

  • false: the synchronization pattern sent a request to suspend the Javascript code of all, until the server until the response is obtained. If the browser when connecting to a network or a fault in time to download the file, the page would have been suspended.
  • true: the request issued asynchronous mode, while data transmission and reception request object, the browser can continue loading the page, perform other Javascript code.

3, the transmission request

xhr.send();

Under normal circumstances, the use of multi-parameter Ajax submission is some simple string, you can use the GET method parameters to be directly submitted written argument to the open method of URL parameters at this time send method is null or empty.

GET request:

xhr.open("GET",demo.php?name=tsrot&age=24,true);
xhr.send(null);

POST request: If you need an HTML form POST data as like, use setRequestHeader () to add the HTTP header. Predetermined data to be transmitted and the send () method:

xhr.open("POST",demo.php,true);
xhr.setRequestHeader("Content-Type","application/x-www-formm-urlencoded;charset=UTF-8");
xhr.send("name"+uerName+"&age="+userAge);

4, the process response

xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status ==200){
    console.log(xhr.responseText);
}
}
  • 0 (uninitialized) or ( request not yet initialized )
  • 1 (Loading) or ( established server links )
  • 2 (loaded successfully) or ( request has been accepted )
  • 3 (interactive) or ( Request Processing )
  • 4 (complete) or ( request has been completed and is ready to respond )

4, complete example

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

In this example:

  • Users click on the "Make a request" button;

  • Call the event handler makeRequest()function;

  • Then the request has passed ( onreadystatechange) to the alertContents()execution.

  • alertContents()Check the returned response is OK, then alert() test.htmlthe file content.

Three, Ajax application scenarios

  • data verification

  • Take data on demand

  • Automatic Updates page

Four, Ajax's strengths and weaknesses

advantage:

  • Without refreshing the page, the user experience is good.
  • Asynchronous communication, faster response capability.
  • Reduce redundant request, reduce the burden on the server.
  • Based on standardized and widely supported technologies, no plug-ins or applets.

Disadvantages:

  • Ajax kill bakc button, the destruction of the browser back mechanism.
  • There are some security issues.
  • Support for the search engines is relatively weak.
  • Destroyed the exception mechanism of the program.
  • URL can not be accessed directly.

Guess you like

Origin www.cnblogs.com/xiaxu/p/11462400.html