This is the 7th day of my participation in Gwen Challenge

AJAX basics and simple action examples

  • What is AJAX?
  • Step 1 – How do I make an HTTP request
  • Step 2 – Process the server response
  • Step 3 – A simple example
  • Step 4 – Use THE XML response
  • Step 5 – Process the data
  • A simple timed XHR example
  • The related content

What is AJAX?

AJAX stands for asynchronous JavaScript and XML. In short, it’s a scripting language that uses XMLHttpRequest objects to communicate with the server side. It can send and receive information in various formats, including JSON, XML, HTML, and text files. The most attractive feature of AJAX is its “asynchronous” nature, which means it can communicate with the server, exchange data and update pages without having to refresh them.

The two main features of AJAX allow you to do the following:

  • Make a request to the server without having to reload the page
  • Receives and processes data from the server

Step 1 – How do I make an HTTP request

In order to make HTTP requests to the server using JavaScript, you need an object instance with the necessary functionality. So that’s where XMLHttpRequest comes from. Its predecessor originated in Internet Explorer and its name is the ActiveX object XMLHTTP. Then, following Mozilla, Safari, and other browsers, you implement an XMLHttpRequest object that supports the methods and properties of Microsoft’s original ActiveX object. At the same time, Microsoft has implemented XMLHttpRequest.

// 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");
}
Copy the code

Note: For illustrative purposes, this is a simplified version of the code used to create an XMLHttp instance. For a more practical example, see Step 3 of this article.

After making the request, you will receive a reply. At this stage, you need to tell the XMLHttp request object which JavaScript function will process the response by setting the properties of the onReadyStatechange object and naming it after calling the function when the request changes state, as follows:

httpRequest.onreadystatechange = nameOfTheFunction;
Copy the code

Notice that there are no parentheses or arguments after the function name, because you are assigning a reference to the function, not actually calling it. Alternatively, you can use JavaScript techniques to dynamically define functions (called “anonymous functions”) to define the operation that will process the response, rather than giving the function name, as follows:

httpRequest.onreadystatechange = function(){
    // Process the server response here.
};
Copy the code

Next, after declaring what happens when the response is received, you need to actually make the request by calling the OPEN () and send() methods of the HTTP request object, as follows:

httpRequest.open('GET'.'http://www.example.org/some.file'.true);
httpRequest.send();
Copy the code
  • The first argument of the callopen()Are HTTP request methods -GET, POST, HEAD or any other method supported by the server. Keep the method in all caps to the HTTP standard, or some browsers (such as Firefox) may not process the request. For more information about possible HTTP request methods, seeThe W3C specification.
  • The second parameter is the URL to which you want to send the request. As a security feature, you cannot invoke urls on third-party domains by default. Make sure you use the correct domain name on all pages, otherwise you will get a “permission denied” error when callingopen(). A common pitfall is to try to call the page by coming to your web site, domain.tldwww.domain.tld. If you do need to send requests to another domain, seeHTTP Access Control (CORS).
  • The optional third parameter sets whether the request is asynchronous. iftrue(default), JavaScript continues to execute, and the user can interact with the page before the server response arrives. This is the first A in AJAX.

Send () If the request is post-ing, the argument to this method can be any data you want to send to the server. Form data should be sent in a format that the server can parse, such as a query string:

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

Or other formats such as multipart/form-data, JSON, XML, etc.

Note that if YOU want to do POST data processing, you may have to set the MIME type of the request. For example, before calling send() to send form data as a query string, use the following command:

httpRequest.setRequestHeader('Content-Type'.'application/x-www-form-urlencoded');
Copy the code

Step 2 – Process the server response

When you send a request, you provide the name of a JavaScript function to process the response:

httpRequest.onreadystatechange = nameOfTheFunction;
Copy the code

What should this feature do? First, the feature needs to check the status of the request. If the value of the status is xmlHttprequest.done (corresponding to 4), the complete server response has been received and you can continue processing it.

if (httpRequest.readyState === XMLHttpRequest.DONE) {
    // Everything is good, the response was received.
} else {
    // Not ready yet.
}
Copy the code

ReadyState value a complete list of records in the XMLHTTPRequest. ReadyState, as shown below:

  • 0 (uninitialized) or (request uninitialized)
  • 1 (loading) or (Server connection established)
  • 2 (loaded) or (request received)
  • 3 (interactive) or (processing request)
  • 4 (Completed) or (Request completed, response ready)

Next, examine the HTTP response status code for the HTTP response. Possible code is listed at W3C. In the following example, we distinguish the success of the AJAX call by examining the 200 OK response code.

if (httpRequest.status === 200) {
    // Perfect!
} else {
    // There was a problem with the request.
    // For example, the response may have a 404 (Not Found)
    // or 500 (Internal Server Error) response code.
}
Copy the code

After checking the status of the request and the HTTP status code of the response, you can do whatever you want with the data sent by the server. You can access this data in two ways:

  • httpRequest.responseText– Returns the server response as a text string
  • httpRequest.responseXML– Treat the response asXMLDocumentObject that can be iterated over using JavaScript DOM functions

Note that the above steps only work if you use an asynchronous request (the third parameter not specified by open() or set it to true). If you use synchronous requests, there is no need to specify the functionality, but it is strongly recommended not to use it as it can lead to a poor user experience.

Step 3 – A simple example

Let’s put this together with a simple HTTP request. Our JavaScript will request an HTML document, test.html, which contains the text “I am a test”. We then alert() the content of the response. Note that this example uses raw JavaScript- no jQuery is involved. In addition, HTML, XML, and PHP files should be placed in the same directory.

<button id="ajaxButton" type="button">Make a request</button>

<script>
(function() {
  var httpRequest;
  document.getElementById("ajaxButton").addEventListener('click', makeRequest);

  function makeRequest(a) {
    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(a) {
    if (httpRequest.readyState === XMLHttpRequest.DONE) {
      if (httpRequest.status === 200) {
        alert(httpRequest.responseText);
      } else {
        alert('There was a problem with the request.'); }}}}) (); </script>Copy the code

In this example:

  • The user clicks the Make a Request button;
  • The event handler invokes thismakeRequest()Functions;
  • Make the request, and then (onreadystatechangeExecute the pass toalertContents();
  • alertContents()Check to see if the response is received, then click OK, and then check the filealert()The content of thetest.html.

Note: If you want to send a request to a piece of code that will return XML instead of a static HTML file, you must set the response header to work in Internet Explorer. If header Content-Type:application/ XML is not set, IE will raise a JavaScript “expected object” error after you try to access the line of an XML element.

Note 2: If you do not set the header, cache-control :no-cache then the browser caches the response and never resubmits the request, which makes debugging a challenge. You can also add always-different GET parameters, such as timestamps or random numbers

Note 3: If httpRequest uses this variable globally, the competing function calls makeRequest() may overwrite each other, resulting in a competing state. Declaring local variables in a closure that contains the AJAX function httpRequest avoids this.

If a communication error occurs (such as a server shutdown), the onReadyStatechange method will throw an exception while accessing the response state. To alleviate this problem, you can change the if… Then statement wrapped in a try… The catch:

function alertContents(a) {
  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); }}Copy the code

Step 4 – Use THE XML response

In the previous example, after receiving a response to an HTTP request, we used the responseTextproperty of the request object, which contains the contents of the test.html file. Now let’s try out the responseXML property.

First, let’s create a valid XML document that we’ll request later. The document (test.xml) contains the following:

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

In the script, we just need to change the request line to:

. onclick="makeRequest('test.xml')">...Copy the code

And then in alertContents(), we need to replace the line with alert(Httprequest.responseText; :

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

This code takes an object given by XMLDocument, responseXML and uses DOM methods to access some of the data contained in the XML document. You can see test.xml and the updated test script.

Step 5 – Process the data

Finally, let’s send some data to the server and receive a response. This time, our JavaScript will request a dynamic page called test.php that will receive the data we send and return a “computed” string- “Hello, [user data]!” – We call it alert().

First, we’ll add a text box to the HTML for the user to enter its name:

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

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

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

We need to modify makeRequest() to accept user data and pass it to the server. We change the request method from GET to POST and include our data as arguments 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));
  }
Copy the code

The function alertContents() can be written in the same way as in Step 3 to warn us of the string we computed (if all this was returned by the server). However, assume that the server will return the calculated string and raw user data. So, if our user types “Jane” in the text box, the server’s response will look like this:

{"userData":"Jane"."computedString":"Hi, Jane!"}
Copy the code

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

function alertContents(a) {
  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.'); }}}Copy the code

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);
Copy the code

For more information about DOM methods, be sure to examine the Document Object Model (DOM).

A simple timed XHR example

Here is another simple example – here we load a text file through XHR, assuming its structure is as follows:

TIME: 312.05
TIME: 312.07
TIME: 312.10
TIME: 312.12
TIME: 312.14
TIME: 312.15
Copy the code

After loading the text file, we split() puts the items into an array of each newline character (\n is basically where each newline character is in the text file), and then prints the full list of timestamps and the last timestamp to the page.

Use setInterval() to repeat the call every 5 seconds. The idea is that some server-side script will constantly update the text file with the new timestamp, and our XHR code will be used to report the latest timestamp on the client side.

<! DOCTYPE html> <html> <head> <meta charset="utf-8">
    <title>XHR log time</title>
    <style>

    </style>
  </head>
  <body>
    <p id="writeData" class="data">Off-Line</p>
    <p id="lastStamp">No Data yet</p>

    <script>

    const fullData = document.getElementById('writeData');
    const lastData = document.getElementById('lastStamp');

    function fetchData(a) {
      console.log('Fetching updated data.');
      let xhr = new XMLHttpRequest();
      xhr.open("GET"."time-log.txt".true);
      xhr.onload = function() {
        updateDisplay(xhr.response);
      }
      xhr.send();
    }

    function updateDisplay(text) {
      fullData.textContent = text;

      let timeArray = text.split('\n');

      // included because some file systems always include a blank line at the end of text files.
      if(timeArray[timeArray.length-1= = =' ') {
        timeArray.pop();
      }

      lastData.textContent = timeArray[timeArray.length-1];
    }

    setInterval(fetchData, 5000);
    </script>
  </body>
</html>
Copy the code

The related content

More relevant articles and my contact information are listed here:

Gitee.com/haiyongcsdn…

And finally, don’t forget ❤ or 📑