Understand Ajax in one article, and attach Ajax interview questions

Time:2022-7-30

catalogue

preface

Hello, everyone, I amWhite ink, a contradiction between learning and rowing.

In the past, when learning ajax, the teacher simply used jQuery for a while and tasted it. After class, I didn’t understand it in depth, and I’m not even proficient in using it. I even thought Ajax was unique to jQuery

Today, I learned again, and finally figured out what AJAX is and how to use it.

First, make a simple note to deepen your memory, most of which are carried, and then supplement it after in-depth understanding in the future.


text

What is Ajax?

Ajax can be found inDo not reload the entire pageIn the case ofExchange data with the server and update some web pages

Ajax = asynchronous JavaScript and XML.

AJAX is not a new programming language, but a new way to use existing standards.


Implementation core / working principle: XMLHttpRequest object

XMLHttpRequest is the foundation of Ajax.

The XMLHttpRequest object is used for sending requests and receiving response data.

All modern browsers support XMLHttpRequest objects (IE5 and IE6 use activexobject).

General usage of XMLHttpRequest

  1. establishXMLHttpRequest object
  2. Send request usingopen()andsend()method
  3. Get the response from the server, using the XMLHttpRequest object’sresponseTextorresponseXMLattribute
  4. The data processing of the server response uses the XMLHttpRequest objectonreadystatechangeattribute

Create XMLHttpRequest object

Syntax for creating XMLHttpRequest object:variable=new XMLHttpRequest();

Older versions of IE5 and IE6 use ActiveX objects:variable=new ActiveXObject("Microsoft.XMLHTTP");

Therefore, if you want to be compatible with IE5 and IE6, you need to determine the browser version before creating the corresponding object. (does such an old browser really need to be compatible?)

var xmlhttp;
If (window.xmlhttprequest) {// judge the browser version
  // code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();// Create XMLHttpRequest object
}else{
  // code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");// Create an activexobject object
}

Send request

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

//Get request
xmlhttp.open("GET","test1.txt?key=value",true);
xmlhttp.send();
//Post request
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");// Request header
xmlhttp.send("fname=Bill&lname=Gates");// data

Method and parameter interpretation

method describe
open(method,url,async) Specify the type of request, URL, and whether to process the request asynchronously.
method: type of request; Get or post
url: location of the file on the server
async: true (asynchronous) or false (synchronous)
send(string) Send the request to the server.
string: it is only used for post requests, and get request parameters are placed in the URL
setRequestHeader(header,value) Add an HTTP header to the request.
header: specify the name of the header
value: specify the value of the header

Ajax refers to asynchronous JavaScript and XML.
If the XMLHttpRequest object is to be used for Ajax, itsopen()MethodicalasyncParameter must be set totrue
thereforeXMLHttpRequest is a technology to implement Ajax, not Ajax, do not confuse.

Note: ifasyncThe parameter is set tofalse, that is, it is non asynchronous, and JavaScript will wait until the server response is ready to continue execution. If the server is busy or slow, the application hangs or stops.


Server response

Get the response from the server, mainly usingXMLHttpRequestObjectresponseTextorresponseXMLProperties.

1. ResponseText attribute

Get the response data in string form and use it directly as a string.

document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

2. Responsexml attribute

To obtain the response data in XML form, you need to parse it as an XML object.

xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("ARTIST");
for (i=0;i";
}
document.getElementById("myDiv").innerHTML=txt;

data processing

When the request is sent to the server, we need to perform some response based tasks, mainly using the XMLHttpRequest objectreadyStateAttributes andonreadystatechangeEvent properties.

1. ReadyState attribute

readyStateAttribute translation isReady status, with XMLHttpRequest storedstatus information , from 0 to 4.

0: request not initialized

1: Server connection established

2: Request received

3: Request processing

4: Request completed and response ready

wheneverreadyStateWhen it changes, it will triggeronreadystatechangeEvent, so these two should be used in combination. Here is onreadystatechange.

2. Onreadystatechange event attribute

onreadystatechangeEvents are used to store functions (or function names) wheneverreadyStateThis function is called when the property changes.
onreadystatechangeThe event will be triggered 5 times (0 – 4), corresponding toreadyStateEvery change of.

3. Status attribute

XMLHttpRequest also has an important attribute:status

statusAttribute represents the return status code of the HTTP request. Because XMLHttpRequest is also a web page of the request, its meaning is the same as that of a traditional web page.

200: normal return

404: page not found

500: server internal error

Next, combine:

//Set the function for onreadystatechange when async=true is used
xmlhttp.onreadystatechange=function(){
  //When readyState equals 4 and the state is 200, the response is ready
  if (xmlhttp.readyState==4 && xmlhttp.status==200){
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
  }
}
xmlhttp.open("GET","test1.txt",true);//async=true
xmlhttp.send();

Note: asynchronous is requiredonreadystatechange, i.eopen()MethodicalasyncThe parameter is set totrueHour. Ifasyncbyfalse, put the code intosend()Just after the statement.

//When async=false is used, the code is put back directly
xmlhttp.open("GET","test1.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

So far, XMLHttpRequest has learned almost. The following is the supplementary content.


Callback function (callback function)

I haven’t figured out the callback function yet

But it doesn’t affect my writing, Hahahahahaha

A callback function is a function that is passed to another function in the form of a parameter.

If there are multiple Ajax tasks on the website, you should write a standard function for creating the XMLHttpRequest object and call this function 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("/ajax/test1.txt",function(){
		if (xmlhttp.readyState==4 && xmlhttp.status==200){
			document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
		}
	});
}

>>W3s instance<<


Interview questions

1. What is Ajax?

  1. Ajax = asynchronous JavaScript and XML.

  2. AJAX is a technology for creating fast dynamic web pages. Traditional web pages (without Ajax) must reload the entire web page if they need to update content. AJAX is a technology that can update some web pages without reloading the whole web page.

  3. Ajax adopts the method of asynchronous request, solves the problem of page non refresh submission, and improves the user experience effect of the page; Commonly used automatic completion prompt, user name repeatability check during registration.

  4. Common Ajax framework: Ajax in jquery

Summary:AJAX is translated into asynchronous JavaScript and XML, which is a web page programming technology of asynchronous submission and local refresh.


2. What are the advantages and disadvantages of Ajax? (please talk about your understanding of Ajax)

advantage:(why use ajax?)

  1. Improve the user experience.Partially refresh the page, reduce users’ psychology and actual waiting time, and bring a better user experience.
  2. Reduce the burden on the server.Get data on demand to minimize redundant requests and reduce server-side processing overhead.
  3. Based on XML standardization, it is widely supported without installing plug-ins, which further promotes the separation of pages and data.

Disadvantages:

  1. There is a browser compatibility problem.Ajax uses a lot of JavaScript and Ajax engines, which depend on the support of the browser. When writing, we should consider the compatibility with the browser.
  2. It destroys the forward and backward functions of the browser.AJAX is only a partial refresh, so the back button of the page is useless.
  3. Not friendly to search engines.Search engines will block all JS code, so the information loaded by Ajax will not be included by search engines.
  4. The support of streaming media and mobile devices is not very good.

3. HTTP status code

200The server successfully returned to the page
404The requested page does not exist
503Service Unavailable

100-199Used to specify some actions corresponding to the client.
200-299Used to indicate that the request was successful
300-399It is used for files that have been moved and is often included in the location header information to specify new address information
400-499Error for expense client
500-599Used to support service errors


4. Working principle of Ajax

  1. Create Ajax objectsXMLHttpRequest/ActiveXObject(Microsoft.XMLHttp)
  2. Judge the data transmission modeGET/POST
  3. Open linkopen()
  4. send outsend()
  5. When the Ajax object completes the fourth step(onreadystatechange)After data receiving, judge the HTTP response status(status)Execute callback function between 200-300 or 304 (CACHE)

5. What is the biggest feature of Ajax?

Ajax can realize asynchronous submission and local refresh, which makes web applications respond to user actions more quickly and avoids sending unchanged information on the network.


6. Please introduce the XMLHttpRequest object?

The core of AJAX is the JavaScript object XMLHttpRequest, which is a technology that supports asynchronous requests. XMLHttpRequest enables programmers to use JavaScript to make requests to the server and process responses without blocking users. Through the XMLHttpRequest object, web developers can locally update the page after it is loaded.
Ajax became popular after Google used “Google Suggest” in 2005.
“Google Suggest” uses the XMLHttpRequest object to create a dynamic web interface:
When the user starts to input Google’s search box, JavaScript sends the characters entered by the user to the server, and then the server returns a list of suggestions.
XMLHttpRequest objects are supported in ie5.0+, Safari 1.2, Mozilla 1.0/firefox, opera 8+ and netscapt7.


7. How to get the XML data responded by the server on the browser side

Responsexml attribute of XMLHttpRequest object


8. Is there any difference in the way XMLHttpRequest objects are created in IE and Firefox?

It is created through new activexobject() in IE and new xmlhttprequest() in Firefox


9. Introduce the common methods and properties of XMLHttpRequest object (the more you answer, the better)

Open () method: establish a call to the server.
Send() method: Send a specific request
Abort() method: stop the current request
ReadyState property: returns the requested state
ResponseText property: the text of the server-side response
Reponsexml attribute: XML of server-side response
Status: HTTP status code of the server


10. What are the components of Ajax technology system?

HTML,css,dom,xml,xmlHttpRequest,javascript


11. What is the difference between Ajax applications and traditional web applications?

Concise statement:
In traditional web applications, the request / response mode is synchronous. That is, when the server is processing the client request, the client needs to wait until the server response returns, and the client can continue to execute.
The request / response of Ajax Application is asynchronous mode, that is, when the server is processing the client request, the client can continue to execute without waiting; When the server response returns, the client will refresh locally.
Detailed description version:
In traditional JavaScript programming, if you want to get the information on the server-side database or file, or send the client-side information to the server, you need to establish an HTML form and then get or post the data to the server. Users need to click the “submit” button to send or accept data information, and then wait for the server to respond to the request, and the page will reload.
Because the server will return a new page every time, traditional web applications may be slow and user interaction is not friendly.
Using Ajax technology, JavaScript can interact directly with the server through the XMLHttpRequest object.
Through HTTP request, a web page can send a request to the web server and accept the information returned by the web server (there is no need to reload the page). The same page is displayed to the user. The user feels that the page is refreshed, and he cannot see the sending request and receiving response in the JavaScript background.


12. How many kinds of callbacks are there in Ajax requests

There are eight kinds of callbacks for Ajax requests

  • onSuccess
  • onFailure
  • onUninitialized
  • onLoading
  • onLoaded
  • onInteractive
  • onComplete
  • onException

13. What is the difference between Ajax and JavaScript?

JavaScript is a script language executed on the browser side. AJAX is a development technology for creating interactive web applications. It uses a series of related technologies, including JavaScript.


14. If he is familiar with an Ajax framework, he may ask how to use it in his program.

ASP. Net Ajax integrates a set of client script library, which makes it compatible with asp Net. Its server-side programming model is simpler than the client-side programming model, and it is easy to compare with the existing asp Net program, usually only drag a few controls in the page to realize complex functions, without understanding the deep working principle. In addition, the asp.netajaxcontroltoolkit programmed on the server side contains a large number of independent Ajax controls and Ajax function extensions to the original asp.net server controls.


15. Programming problem: write a simple $ How is Ajax () requested? (Ajax template of jQuery)

$.ajax({
    url:' http://www.baidu.com ', // request address
    Type:'post', //post request
    Data:data, // pass the past data at the same time as the request
    Cache:true, // whether to cache this page
    headers:{}, 			
    Datatype: 'JSON', // return data type: xml/json/html/script
    BeforeSend: function() {}, // the function executed before sending the request
    Success: function() {}, // callback function after successful request
    Error: function() {}, // the function called when the request fails
    Complete:function() {} // call back the function after the request is completed
});

Written references

W3s Ajax tutorialStation attribute


Postscript

Well, this article is over! If it helps you, you can give it to meLike + favorite + follow! Your encouragement is my motivation to update!

Recommended Today

JS generate guid method

JS generate guid method https://blog.csdn.net/Alive_tree/article/details/87942348 Globally unique identification(GUID) is an algorithm generatedBinaryCount Reg128 bitsNumber ofidentifier , GUID is mainly used in networks or systems with multiple nodes and computers. Ideally, any computational geometry computer cluster will not generate two identical guids, and the total number of guids is2^128In theory, it is difficult to make two […]