AJAX-----Basic

AJAX

How Ajax Works

synchronous and asynchronous

Synchronous submission: When the user sends a request, the current page cannot be used, the server responds to the page to the client, and the user can use the page only after the response is completed.

Asynchronous submission: When the user sends a request, the current page can continue to be used. When the data of the asynchronous request is responded to the page, the page displays the data.

need to know some knowledge

URL

A URL address consists of three parts

 传输协议
 域名
 端⼝号

Transfer Protocol

  • Our common transport protocols are http and https
  • But http is a common protocol, not very secure
  • https is an encrypted transmission protocol

domain name

The domain name represents the IP address of the computer at the other end of the network

In fact, which server we want to access

port number

  • Just finding the server computer is not enough, you have to find the right folder
  • Everyone numbered the folders and stored them from 0 to 255, a total of 256
  • Each folder also has corresponding small folders 0 ~ 255, a total of 256
  • Then there are 256 * 256 folders in total, that is, from 0 to 65535
  • So we have 65536 port numbers, corresponding to 0 ~ 65535
  • Everyone regards port 80 as the default port number of a website
  • The http protocol defaults to port 80
  • The https protocol defaults to port 443

XML

It is an extensible markup language designed to transmit and store data, all of which are custom tags

HTTP

response message, request message

Create an XMLHttpRequest object

variable = new XMLHttpRequest();
vairable = new ActiveXObject("Microsoft.XMLHTTP");//老版本(IE5和IE6)

send a request to the server

xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
//XMLHttpRequest对象的open()和send()方法

open(method,url,async)

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

send(string)

  • string : only for POST requests
GET POST ?

GET is simpler and faster than POST, and works in most cases.

However, use a POST request in the following cases:

  • Reluctance to use cached files (update files or databases on the 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
GET
xmlhttp.open("GET","/try/ajax/demo_get.php",true);  //一个简单的GET请求
xmlhttp.open("GET","/try/ajax/demo_get.php?=" + Math.random(),true) //向 URL 添加一个唯一的ID
xmlhttp.open("GET","/try/ajax/demo_get.php?fname=Henry&lname=Ford",true)   //通过GET 方法添加信息
//===================jQuery中的get post=================================通过 HTTP 请求加载远程数据
$.get('url',{
    
    a:100, b:300}, function() {
    
    
    //函数体
    //get 请求的参数就直接在 url 后面进行拼接就可以
})
$.post('url',{
    
    a:100, b:300}, function() {
    
    
    //函数体
    //post 请求的参数是携带在请求体中的,所以不需要再 url 后面拼接
})
//======================================
$.ajax({
    
    
    //URL
    url:  ,
    //参数
    data: {
    
    a:2, b:30},
    //请求类型
    type:,
    //响应体结果
    dataType: 'json',
    //成功的回调
    success: function(data) {
    
    
    
	},
	//超时时间
	timeout: 3000,
     //失败的回调
    error: function() {
    
    
            
    }
})
POST
xmlhttp.open("POST","/try/ajax/demo_post.php",true); //一个简单的POST请求
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded")   //("名字","值")
xmlhttp.send("fname=Henry&lname=Ford");

setRequestHeader

Usually in the HTTP protocol, when the client obtains a certain web page like the server, it must send a header file of the HTTP protocol to tell the server what information the client wants to download and related parameters.

XMLHTTP obtains the file data on the website through the HTTP protocol, so it also needs to send the HTTP header to the server.
However, some parameters of XMLHTTP may not be specified in the HTTP header by default. This is when we need to modify or add these parameters and use the setRequestHeader method.

The setRequestHeader method is just an interface method provided by XMLHTTP for adding or modifying HTTP headers. CONTENT-TYPE:application/x-www-form-urlencodedIt means that the encoding method of the text content submitted by the client to the server is URL encoding, that is, in addition to standard characters, each byte is in double-byte hexadecimal Add a "%" before it.

There is no submission content in the GET method, and the way to pass parameters in GET is to transmit them through virtual addresses. For example: there are GET /bb.asp?www=1234 HTTP/1.1
only "www=1234"so many parameters;

POST is to put parameters behind HTTP

setRequestHeader(header,value) : header specifies the name of the header; value : specifies the value of the header

all

server response

responseText

If the response from the server is not XML, use the responseText property

The responseText property returns the response as a string

responseXML

If the response from the server is XML and needs to be parsed as an XML object, use the responseXML attribute

responseType = 'json'; automatic conversion

onreadystatechange event

In the onreadystatechange event, we specify what to do when the server response is ready to be processed .

Three important attributes of the XMLHttpRequest object
onreadystatechange Store the function (or function name), which will be called whenever the readyState property changes
readyState Holds the state of the XMLHttpRequest. Varies from 0 to 4.
status 200: "OK" 404: Page not found

Whenever the readyState changes, the onreadystatechange event will be triggered (0-1,1-2,2-3,3-4)

  • 0: request is not initialized
  • 1: server connection established
  • 2: Request accepted
  • 3: Request processing
  • 4: The request is also complete, and the response is ready

When readyState is equal to 4 and the status is 200, it means that the response is ready:

xmlhttp.onreadystatechange=function() {
    
    
    if(xmlhttp.readyState==4 && xmlhttp.status==200) {
    
    
        //
    }
}

A callback function is a function that is passed as an argument to another function.

If you have multiple AJAX tasks on your site, you should write a standard function for creating an XMLHttpRequest object and call that function for each AJAX task.

The function call should contain the URL and the task to execute when the onreadystatechange event occurs (each call may be different)

ASP/PHP

Fix caching issues

open("GET","url?t="+Date.now())

Request timeout network exception handling

//延时响应

setTimeout(() => {

​	//设置响应体  设置允许跨域

	response.send('');

},3000)
    // 1. 创建对象
            const xhr = new XMLHttpRequest();
            //超时设置   2s设置
            xhr.timeout = 2000;
            //超时回调
            xhr.ontimeout = function() {
    
    

            }
            //网络异常
            xhr.onerror = function() {
    
    
                
            }

abort() cancels the request

Request to resend the question

// 假设有一个按钮控制着发送请求
const btn = document.querySelector('button');
let x = null;
let isSending = false;  // 是否正在发送请求
btn.onclick = function() {
    
    
    if(isSending) {
    
    
        x.abort(); //如果正在发送,则取消该请求,创建一个 新请求
        x = new XMLHttpRequest();
        //修改 isSending 的值
        isSending = true;
        x.open("GET","URL");
        x.send();
        ...
    }
}

Axios function

axios.defaults.baseURL = "";
axios.get("",{
    
    
	params: {
    
    
	
	},
	headers: {
    
    
	
	},
	...
})
//===========没搞明白
axios.post("",{
    
    
	...
})

Guess you like

Origin blog.csdn.net/m0_63300737/article/details/123305858