Ajax technology and its use steps, synchronous and asynchronous methods, and request methods

Synchronous, Asynchronous

Before introducing AJAX technology, we must first understand the concept of synchronous request and asynchronous request.

1. Synchronous request:

Concept: After the sender sends a request, it needs to wait for the receiver to send back a response. Before sending back a response, any operation on the user interface is invalid. Only after waiting for the receiver to send back a response can it respond to user interaction and send the following A data packet communication method.

发送请求 --> 等待服务器处理请求(当前浏览器的任何操作无效) --> 处理完毕返回
2. Asynchronous request:

Concept: After the sender sends the request, there will be a separate sub-thread to request data, and the main thread still responds to the user interaction, so at this time the user interaction is processed, the user operates smoothly, the user experience is better, and there is no need to wait for the receiver The communication method of sending the next data packet directly.

发送请求 --> 服务器处理(浏览器可以进行别的操作) --> 处理完毕

Request method (GET, POST)

When the synchronous and asynchronous methods are introduced, two request methods are also introduced:

1. GET request method
  1. get is to get data from the server.
  2. get is to add the parameter data queue to the URL pointed to by the ACTION attribute of the submitted form, and the value corresponds to each field in the form, which can be seen in the URL. But because it appears in the URL, there are security risks.
  3. For the get method, the server uses Request.QueryString to obtain the value of the variable.
  4. The amount of data transferred by get is small and cannot be larger than 2KB.
    5 get very low security.
2. POST request method
  1. post is to send data to the server.
  2. Post is through the HTTP post mechanism, each field in the form and its content are placed in the HTML
    HEADER and sent to the URL address pointed to by the ACTION attribute. The user cannot see this process.
  3. For the post method, the server uses Request.Form to obtain the submitted data.
  4. The amount of data transmitted by post is relatively large, and is generally defaulted to be unlimited. But in theory, the maximum amount is 80KB in IIS4 and 100KB in IIS5.
  5. Post security is high.

Since the post method does not include the parameters in the URL, and the post method is safer than the get method, it hides the parameters. We can click the developer option of the browser to enter the network section, and then we can view the submitted data.
As shown below:
write picture description here

Note: Since you can use the packet capture tools Fiddler, Charles, etc. to capture data packets, you can also view the submitted data, so the post method is not absolutely safe.

Introduction to Ajax Technology

From synchronous and asynchronous methods, as well as get and post request methods, we can lead to our AJAX technology:

Asynchronous JavaScript and XML

AJAX is a combination of existing technologies, a technology that supports asynchronous requests. The core is the js object - XMLHttpRequest.

Advantages:
1. You can exchange data with the server and update part of the web page content without reloading the entire page.
2. No browser plug-ins are required, only JavaScript can be executed in the browser.

In the browser, we can obtain new content through ajax technology without refreshing the page, just like QQ space dynamics can never be refreshed.

The use steps and related applications of AJAX technology

1. How it works (AJAX application model)

write picture description here

2. The steps of using AJAX

Five parts:

1) Create an asynchronous object (XMLHTTPRequest)

//创建异步对象
var ajax = new XMLHttpRequest();

2) Set the method and url (open() method)

//设置跟服务端交互的信息
ajax.open('get','ajax.php?userName=jack');

Note: If you use post to submit data, you must add a sentence (add this sentence before sending the request)

ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");

3) Send a request (send() method)

Browser ———–> Request message ———–> Server

The server will then create a php file, get the uploaded data (optional), and return it to the user.

//发送请求
ajax.send();

4) Register the event

//接受服务器反馈
    ajax.onreadystatechange = function () {
      //为判断服务器是否做出正确反应
      if(ajax.readyState == 4 && ajax.status == 200 ) {
        //打印相应内容
        console.log(ajax.responseText);
      }
    }

5) Get the returned data in the event and modify the page display

Server——Response message——>Get the returned data in the event, modify the page display

3. Detailed usage of the five parts of AJAX

1) Create an XMLHttpRequest object (compatible writing)

//新版本浏览器
var ajax = new XMLHttpRequest();

//IE5,6
var ajax = new ActiveXObject("Microsoft.XMLHTTP");

So compatibility is written:

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

2) Send the request

  • open( method,url,async)

    • method: the type of request, GET or POST
    • url: the location of the file on the server
    • async: true (asynchronous), false (asynchronous)
  • send()

3) Notes on the POST method

If the form form uses the post method to submit data, you must use the setRequestHeader() method of the XMLHttpRequest object. To add the http header, and then use the send method to add the data you want to send.

//发送与服务器端交互的信息
ajax.open("POST","ajax_test.php",true);
//设置http头
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
//发送请求
ajax.send("fname=Bill&lname=Gates");

4) onreadystatechange() event (this event is called when the readyState property changes)

  • readyState: the state of the XMLHttpRequest object
attribute value object state
0 request not initialized
1 request has been created
2 request received
3 request processing
4 The request is complete and the response is ready (required state)
  • status:
attribute value condition
200 "OK, the page exists"
404 "Page not found"

5) Server response content

If the response is a normal string, use responseText, if the response is XML, use responseXML.

  • responseText: Get the response data in the form of a string
  • responseXML: Get response data in XML form

Here we need to introduce responseText and responseXML in detail.

① responseText (the obtained data is in the form of a string)

Get the whole content as a string

console.log(ajax.responseText);//将得到一个字符串
② responseXML (an xml object)

responseXML is a special attribute used to get the xml object

Note: The xml object is a document object on the browser side, and document syntax such as querySelector or getElementById can be used directly when parsing

console.log(ajax.responseXML);//将得到一个document对象
console.log(ajax.responseXML.querySelector('name').innerHTML);

Among them:
XML file format: define the key value by yourself, and the key exists in the form of double tags

1. 开头 
       <?xml version="1.0" encoding="UTF-8"?>
2. 根节点 如:
       <person></person>
3. 若干子节点: 
       <name>王狗蛋</name>
       <age>15</age>
       <sex></sex>
       <hobby>eating</hobby>
       <skill>play games</skill>
    <?xml version="1.0" encoding="UTF-8"?>
    <person>
        <name>王狗蛋</name>
        <age>15</age>
        <sex></sex>
        <hobby>eating</hobby>
        <skill>play games</skill>
    </person>
③ xml format

When you need to use responseXML, you need to understand the format of XML.

  • is a string written in a certain format
  • Write the version number at the beginning (optional)
  • Use double tags all the way
  • The outermost layer needs to write a root node
  • The name of the tag can be written arbitrarily
    • Cannot start with a number
    • Chinese cannot be used
  • If the version number is written, it should be placed on the first line

4. Use ajax case

1) ajax--get method

<h2>ajax请求 --- get方式</h2>
<input type="text" class='user' >
<input type="button" class='btnAjax' value='发送ajax请求'>
<script>
    var btn = document.querySelector(".btnAjax");
    var userName = document.querySelector('.user');
    //按钮的点击事件
    btn.onclick = function () {
        //创建异步对象
        var ajax = new XMLHttpRequest();
        //设置method和url(利用open方法)
        //url内的key要和php文件中$_GET['key']中的key一样
        ajax.open('get', '01.php?name='+userName.value);
        //发送ajax请求
        ajax.send();
        //注册事件 
        //onreadystatechange()
        ajax.onreadystatechange = function () {
            if(ajax.readyState == 4 && ajax.status == 200) {
                console.log(ajax.responseText);
            }
        }
    }
</script>

01.php page

header("content-type:text/html;charset=utf-8");
echo $_GET["name"].'欢迎你!!';

2) ajax——-post method

Similar to the get method, with only two differences

  • You need to add a sentence before sending the request (before the send method)
//post方式发送数据,需要利用setRequestHeader()来声明http头
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
  • The data requested by the post method is placed in the send() method.
    Format : ('name=jack&age=18')
//在send方法中来规定希望发送的数据
ajax.send('name='+inpContent.value);

ajax(), get() and post() methods in jQuery

There are three ways to implement Ajax function in jquery:

1. $.ajax()

There are the following parameters:

parameter name Parameter Description
data Specifies the data sent to the server
dataType Specifies the type of data returned by the server (xml, html, script, json, jsonp, text)
success The method called after the request is successful
url Specifies which URL to send the request to
type Decide which request method - (post or get)
error Method called when the request fails
sendBefore Callback function (called before the request is sent)

Notice:

  1. If the value of dataType is json, it will automatically generate a js object internally
  2. In the sendBefore callback function, if return false, the request will be canceled

The specific code is as follows:

$.ajax({      
    url: 'demo.php',
    type: 'post',
    data: 'name=zhangsan',
//dataType的使用,如果服务器发来的数据和dataType属性值不同的话,会出现乱码
    dataType: 'text',
    success: function (data) {
         console.log(data);
    },
    beforeSend: function () {
          console.log('发送之前调用');
         //return false;将取消这次请求
    },
    error: function () {
         console.log('请求失败了!');
    }
});
2. $.get()

格式:$.get(url,data,success(data){},dataType)

parameter:

parameter name Parameter Description
url Specifies which URL to send the request to
data Specifies the data to be sent to the server along with the request, and supports the format of writing the data as a js object
success(data) Callback function, the function to be called when the request is successful
dataType The type of data obtained from the server

The specific code is as follows:

$.get('demo.php',{name:'zhangsan',age:'18'},function (data){
      console.log(data);
  },'text');
3. $.post()

Format: $.post(url,data,success(data){},dataType)
Parameters:

parameter name Parameter Description
url Specifies which URL to send the request to
data Specifies the data to be sent to the server along with the request, and supports the format of writing the data as a js object
success(data) Callback function, the function to be called when the request is successful
dataType The type of data obtained from the server

The specific code is as follows:

$.post('demo.php',{name:'zhangsan',age:'18'},function (data){
    console.log(data);
},'text');

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325681347&siteId=291194637