Ajax definition: Asynchronous JavaScript and XML, which means to use JavaScript to execute asynchronous network requests, is a technology that can update part of the web page without reloading the entire web page
Ajax function: To allow the user to stay on the current page and make a new HTTP request at the same time, the new request must be sent with JavaScript. After receiving the data, the page is updated with JavaScript, so that the user feels that he is still staying in the current page. Page, but the data can be constantly updated
Ajax principle: an event occurs in the browser first, such as a click. At this time, js creates an XMLHttpRequest object and sends a request. The server processes the request and returns data. At this time, the js process returns and updates the page.
Initialize/create an XMLHttpRequest asynchronous object
var xmlhttp;
xmlhttp =newXMLHttpRequest();//初始化,创建对象
Set callback function
xmlhttp.onreadystatechange=callback;//响应回掉/监听
Use the open() method to establish a connection with the server
// get
xmlhttp.open("GET",url,true);// post
xmlhttp.open("POST",url,true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded")// 设置请求头
functioncallback(){
// 判断异步对象的状态if(xmlhttp.readyState ==4){
// 判断交互是否成功if(xmlhttp.status ==200){
// 获取服务器响应的数据var res = xmlhttp.responseText
// 解析数据
res =JSON.parse(res)}}}
XMLHttpRequest
There are five possible values for xmlhttp.readyState:
0 (Uninitialized): The (XMLHttpRequest) object has been created, but the open() method has not been called.
1 (Load): The open() method has been called, but the request has not been sent yet.
2 (Load complete): The request has been sent.
3 (Interactive): Partial response data can be received.
4 (Completed): All data has been received and the connection has been closed.
xmlhttp.status: same as http/https request return status
200: Successful response
Landing case (xhr)
Description: A page with a user name, password and login button. After clicking the login button through ajax, it is judged whether the login is successful, and the page does not refresh