Working principle of Ajax and analysis of its advantages and disadvantages

Time:2020-9-26

1. What is Ajax?

The full name is asynchronous JavaScript and XML, which is a combination of existing technologies. It is mainly used to achieve the asynchronous communication effect between the client and the server (without reloading the whole web page), and realize the local refresh of the page.

Through a small amount of data exchange with the server in the background, AJAX can make the web pages update asynchronously to create fast dynamic web pages.

Early browsers can’t support Ajax natively. They can use iframe to achieve asynchronous effect in disguise. Later browsers provide native support for Ajax.

2. How Ajax works

Using Ajax native way to send requests, mainly through XMLHttpRequest (IE7 +, Firefox, chrome, Safari and opera), activexobject (IE5 and IE6) objects to achieve asynchronous communication effect.

Create the XMLHttpRequest object:

var xhr;
if (window.XMLHttpRequest)
{
  //IE7 +, Firefox, chrome, opera, Safari browser execution code
  xhr=new XMLHttpRequest();
}
else
{
  //IE6, IE5 browser execution code
  xhr=new ActiveXObject("Microsoft.XMLHTTP");
}

Send a request to the server: use the open () and send () methods of the XMLHttpRequest object

//Send information through get method, please add information to URL
xhr.open("GET","/try/ajax/demo_get2.php?fname=Henry&lname=Ford",true);
xhr.send();

//Post data like HTML forms, and use setrequestheader() to add HTTP headers
xhr.open("POST","/try/ajax/demo_post2.php",true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.send("fname=Henry&lname=Ford");

//When async = true, you need to specify the function to execute when the response is in the ready state in the onreadystatechange event
xhr.onreadystatechange=function()
{
  if (xhr.readyState==4 && xhr.status==200)
  {
    document.getElementById("myDiv").innerHTML=xhr.responseText;
  }
}
xhr.open("GET","/try/ajax/ajax_info.txt",true);
xhr.send();

//When you use async = false, just put the code after the send () statement. It is not recommended
xhr.open("GET","/try/ajax/ajax_info.txt",false);
xhr.send();
document.getElementById("myDiv").innerHTML=xhr.responseText;

Use get or post?

Get is simpler and faster than post, and works in most cases.

Get is simpler and faster than post, and works in most cases.

However, use a post request in the following situations:

Cannot use cache file (update file or database on server)
Send a large amount of data to the server (post has no data limit)
Post is more stable and reliable than get when sending user input containing unknown characters

//The response from the server is not XML. Use the responseText property to return the response in the form of a string
document.getElementById("myDiv").innerHTML=xhr.responseText;

//The response from the server is XML and needs to be parsed as an XML object, using the responsexml attribute to request CD_ catalog.xml  File and parse the response
xmlDoc=xhr.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("ARTIST");
for (i=0;i<x.length;i++)
{
  txt=txt + x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("myDiv").innerHTML=txt;

On readystatechange event: when a request is sent to the server, we need to perform some response based tasks. Whenever the readyState changes, the onreadystatechange event is triggered.

//When readyState equals 4 and the state is 200, the response is ready
xhr.onreadystatechange=function()
{
  if (xhr.readyState==4 && xhr.status==200)
  {
    document.getElementById("myDiv").innerHTML=xhr.responseText;
  }
}
//If there are multiple Ajax tasks, you should write a standard function for creating an XMLHttpRequest object and call it for each Ajax task. The function call should contain the URL and the task to be performed when the onreadystatechange event occurs (each call may be different)
function myFunction()
{
  loadXMLDoc("/try/ajax/ajax_info.txt",function()
  {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
      document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  });
}

xhr.readyState Value and explanation of:

0: the request is not initialized (open() has not been called yet).

1: The request has been established, but has not been sent (send() has not been called yet).

2: The request has been sent and is being processed (usually the content header can now be obtained from the response).

3: The request is in process; usually some data is available in the response, but the server has not finished generating the response.

4: The response is complete; you can get and use the response from the server.

xhr.status Value and explanation of:

100 – the customer must continue to make requests

101 — the client requires the server to convert the HTTP protocol version according to the request

200 – successful transaction

201 — prompt for new file URL

202 – accepted and processed but not completed

203 — uncertain or incomplete information returned

204 — request received, but return message is empty

205 — the server has completed the request and the user agent must reset the currently browsed files

206 — the server has completed a get request from some users

300 – requested resources are available in multiple locations

301 — delete request data

302 — request data found at other address

303 – suggest customers visit other URLs or access methods

304 — the client has performed a get, but the file has not changed

305 — the requested resource must be obtained from the address specified by the server

306 — the code used in the previous version of HTTP is no longer used in the current version

307 — declare the requested temporary deletion of resources

400 — error request, such as syntax error

401 – request authorization failed

402 — retain valid chargeto header response

403 – request not allowed

404 – no files, queries or URLs found

405 – the method defined by the user in the request line field is not allowed

406 — the request resource is not accessible according to the accept drag sent by the user

407 – similar to 401, the user must first be authorized on the proxy server

408 — the client did not complete the request within the user specified starvation time

409 — the request cannot be completed for the current resource state

410 — the resource is no longer available on the server and no further reference address is available

411 — the server rejects a user-defined request for the content length property

412 – one or more request header fields have errors in the current request

413 — the requested resource is larger than the size allowed by the server

414 — the requested resource URL is longer than the length allowed by the server

415 — request resource does not support request item format

416 — the request contains the range request header field. There is no range indication value in the current request resource range, and the request does not contain if range request header field

417 — the server does not meet the expected value specified in the request expect header field. If it is a proxy server, the next level server may not meet the request

500 – the server has an internal error

501 — the server does not support the requested function

502 — the server is temporarily unavailable, sometimes to prevent system overload

503 – server overloaded or maintenance suspended

504 — the gateway is overloaded, and the server uses another gateway or service to respond to the user, and the set waiting time is long

505 — the server does not support or reject the HTTP version specified in the request header

1XX: information response class, indicating that the request is received and continues processing

2XX: process successful response class, indicating that the action has been successfully received, understood and accepted

3xx: redirection response class, must accept further processing in order to complete the specified action

4xx: client error, client request contains syntax error or could not be executed correctly

5xx: server error, the server can not correctly execute a correct request

3. Advantages and disadvantages of Ajax

advantage:1. No refresh update data: maintain communication with the server without refreshing the whole page

2. Asynchronous communication with the server: communicate with the server asynchronously without interrupting the user’s operation

3. Front end and back-end load balancing: move some back-end work to the front-end to reduce the burden of server and bandwidth

4. It is widely supported based on the specification: there is no need to download browser plug-ins or applets, but the client needs to allow JavaScript to execute on the browser.

5. Interface and application separation: Ajax separates interface from application, that is, data and presentation are separated

Disadvantages:1. Ajax does not support the back and history functions, that is, it destroys the browser mechanism: in the case of dynamically updating the page, the user cannot return to the page state of the previous page, because the browser can only remember the static page in the history

2. Security issues: Ajax technology not only brings users a good user experience, but also brings new security threats to IT enterprises. Ajax technology is just like establishing a direct channel for enterprise data. This allows developers to inadvertently expose more data and server logic than before. The logic of Ajax can hide the security scanning technology of the client, allowing hackers to create new attacks from the remote server. In addition, AJAX is also difficult to avoid some known security weaknesses, such as cross site footstep attacks, SQL injection attacks and security vulnerabilities based on credentials.

3. Weak support for search engine: if not used properly, AJAX will increase the network data traffic, thus reducing the performance of the whole system. Solution: you can use the server to render first.

4. Break the exception handling mechanism of the program

5. Violate the original intention of URL and resource location

6. Can’t support mobile devices well

7. The client side is too large, and too many client segments cause the cost of development

4. application scenarios

1. Load data dynamically and obtain data on demand. [tree menu, linkage menu… / provincial and municipal linkage]

2. Improve user experience. [prompt before input, upload file with progress bar…]

3. E-commerce application. [shopping cart, mail subscription…]

4. Access to third party services. [visit search service, RSS reader]

5. Refresh the layout of data

Not suitable for search, basic navigation, replacing large amounts of text, part of a simple form

The above is the whole content of this article, I hope to help you in your study, and I hope you can support developeppaer more.