Technology Sharing

AJAX learning notes (for personal use)

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

AJAX

Native AJAX

1.1 Introduction to AJAX

AJAX stands for Asynchronous JavaScript And XML. AJAX allows you to send asynchronous requests to the server in the browser. The biggest advantage is that you can get data without refreshing. AJAX is not a new programming language, but a new way to combine existing standards.

1.2 Introduction to XML

XML Extensible Markup Language.
XML is designed for transmitting and storing data.
XML is similar to HTML, the difference is that HTML has predefined tags, while XML has no predefined tags. All of them are custom tags used to mark some data.

<student>
	<name>John</name>
	<age>18</age>
</student>
  • 1
  • 2
  • 3
  • 4

It has now been replaced by JSON.

{"name":"John","age":18}
  • 1

1.3 Characteristics of AJAX

1.3.1 Advantages of AJAX

1) You can communicate with the server without refreshing the page
2) Allows you to update part of the page content based on user events

1.3.2 Disadvantages of AJAX

1) No browsing history, no way to go back
2) There is a cross-domain problem (same origin)
3) SEO unfriendly (webpage content cannot be crawled)

1.4HTTP

HTTP (Hypertext Transport Protocol) protocol [Hypertext Transfer Protocol], the protocol specifies in detail the rules for communication between browsers and World Wide Web servers.

1.4.1 Request Message

The focus is on format and parameters

行	GET  /s?ie=utf-8  HTTP/1.1
头	Host: atguigu.com
	Cookie: name=guigu
	Content-type: application/x-www-form-urlencoded
	user-Agent: chrome 83
空行
体	username=admin&password=admin
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
1.4.2 Response Message
行	HTTP/1.1  200  OK
头	Content-Type: text/html;charset=utf-8
	 Content-length: 2048
	 Content-encoding: gzip
空行
体	<html>
		<head>
		</head>
		<body>
			<h1>HHHHello</h1>
		</body>
	</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12

Note:

Send a GET request: Open the network in the page inspection, refresh the page, send a request, receive a response, open the top request, and the Header contains the Response Header, Request Header, and Query String Parameters. The Query String Parameters contains the result of parsing the content in the requested URL, the Request Header contains the location of the request line and request header, the Response Header contains the response line and response header, and clicking Response is the response body.

Send a POST request: The Query String Parameters in the Headers will become others.

XHR is the abbreviation of XMLHttpRequest. XHR in the web page inspection network is a filter for AJAX requests.

AJAX sends a GET request with parameters in the URL. First separate them with question marks, then write them directly and connect them with &

http:127.0.0.1:8080/server?a=100&b=200&c=300
  • 1

AJAX sends a GET request with parameters in xhr.send()

//3.发送
xhr.send('a=100&b=200&c=300');
xhr.send('a:100&b:200&c:300');
xhr.send('1231212313');
  • 1
  • 2
  • 3
  • 4

AJAX sends a GET request

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX GET 请求</title>
    <style>
        #result{
            width: 200px;
            height: 100px;
            border: solid 1px #90b;
        }
    </style>
</head>
<body>
    <button>点击发送请求</button>
    <div id="result"></div>

    <script>
        //获取button元素
        const btn=document.getElementsByTagName('button')[0];
        const result=document.getElementById('result')
        //绑定事件
        btn.onclick=function(){
            //1.创建对象
            const xhr=new XMLHttpRequest();
            //2.初始化 设置请求方法和url
            xhr.open('GET','http://127.0.0.1:8000/server?a=100&b=200');
            //3.发送
            xhr.send();
            //4.事件绑定 处理服务端返回的结果
            //on  when 当...时候
            //readystate是xhr对象中的属性,表示状态0,1,2,3,4
            //change 改变
            xhr.onreadystatechange=function(){
                //判断(服务端返回了所有的结果)
                if(xhr.readyState===4){
                    //判断响应状态码 200 404 403 401 500
                    //2xx 都是成功
                    if(xhr.status >= 200 && xhr.status<300){
                        //处理结果 行 头 空行 体 
                        //1.响应行
                        // console.log(xhr.status);//状态码
                        // console.log(xhr.statusText);//状态字符串
                        // console.log(xhr.getAllResponseHeaders());//所有响应头
                        // console.log(xhr.response);//响应体

                        result.innerHTML=xhr.response
                    }else{

                    }
                }
            }

        }
    </script>
</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58

AJAX sends a POST request

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX POST 请求</title>
    <style>
        #result{
            width: 200px;
            height: 100px;
            border: solid 1px #903;
        }
    </style>
</head>
<body>
    <div id="result"></div>
    <script>
        //获取元素对象
        const result=document.getElementById("result");
        //绑定事件
        result.addEventListener("mouseover",function(){
            //1.创建对象
            const xhr=new XMLHttpRequest()
            //2.初始化 设置类型与URL
            xhr.open('POST','http://127.0.0.1:8000/server');
            //3.发送
            xhr.send('a=100&b=200&c=300');
            //4.事件绑定
            xhr.onreadystatechange=function(){
                //判断
                if(xhr.readyState===4){
                    if(xhr.status>=200&&xhr.status<300){
                        //处理服务端返回的结果
                        result.innerHTML=xhr.response;
                    }
                }
            }
        })
    </script>
</body>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41

The corresponding backend server.js

const express=require('express')

//创建应用对象
const app=express()

//创建路由规则
//req是对请求报文的封装
//res是对响应报文的封装
app.get('/server',(req,res)=>{
    //设置响应头,设置允许跨域
    res.setHeader('Access-Control-Allow-Origin','*');
    //设置响应体
    res.send('ok');
})

app.post('/server',(req,res)=>{
    //设置响应头,设置允许跨域
    res.setHeader('Access-Control-Allow-Origin','*');
    //设置响应体
    res.send('okkkk');
})

//监听端口启动服务
app.listen(8000,()=>{
    console.log("服务已经启动,8000端口启动中。。。")
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

Custom request headers

//自定义请求头,需要在后端设置好,否则会报错
xhr.setRequestHeader('name','hhhhhh')
  • 1
  • 2

Corresponding backend settings

//可以接收任意类型的请求
app.all('/server',(req,res)=>{
    //设置响应头,设置允许跨域
    res.setHeader('Access-Control-Allow-Origin','*');
    //响应体
    res.setHeader('Access-Control-Allow-Headers','*');
    //设置响应体
    res.send('okkkk');
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

First, res.setHeader('Access-Control-Allow-Headers','*'); is used to receive all response headers. Then app.all is used to receive any type of request. Because options type requests will be returned and no response can be obtained, it is changed to all reception.

The server responds with JSON data

app.all('/json-server',(req,res)=>{
    //设置响应头,设置允许跨域
    res.setHeader('Access-Control-Allow-Origin','*');
    //响应头
    res.setHeader('Access-Control-Allow-Headers','*');
    //响应一个数据
    const data={
        name:'hoshi'
    };
    //对对象进行字符串转换
    let str=JSON.stringify(data);
    //设置响应体
    res.send(str)
})
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

The response body can only contain strings or buffers, so the type must be converted.
The client receives a string, which can be converted into a JSON object in two ways: automatic conversion and manual conversion.
Manual conversion:

const data=JSON.parse(xhr.response)
result.innerHTML=data.name;
  • 1
  • 2

Automatic conversion:

 //设置响应体数的类型
xhr.responseType='json';
result.innerHTML=xhr.response.name;
  • 1
  • 2
  • 3