An article about AJAX

1. Native AJAX

1. Introduction to AJAX

The full name of AJAX is Asynchronous JavaScript And XML, which is asynchronous JS and XML. AJAX can send an asynchronous request to the server in the browser, the biggest advantage: get data without refreshing . AJAX is not a new programming language, but a new way of combining existing standards.

# HTTP
HTTP(hypertext transport protocol)协议『超文本传输协议』,协议详细规定了浏览器和万维网服务器之间互相通信的规则。
约定, 规则

## 请求报文
重点是格式与参数
```
行      POST  /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
```

## 响应报文
```
行      HTTP/1.1  200  OK
头      Content-Type: text/html;charset=utf-8
        Content-length: 2048
        Content-encoding: gzip
空行    
体      <html>
            <head>
            </head>
            <body>
                <h1>Ajax测试</h1>
            </body>
        </html>
```
* 404
* 403
* 401
* 500
* 200

2. Introduction to XML

XML Extensible Markup Language.

XML was designed to transmit and store data.

XML is similar to HTML, the difference is that there are predefined tags in HTML, but there are no predefined tags in XML, all are custom tags, used to represent some data

Say I have a student data:

name = "Monkey King" ; age = 18 ; gender = "Male" ;

Represented in XML:

<student>

      <name>Monkey King</name>

     <age>18</age>

     <gender>男</gender>

</student>

has now been replaced by JSON

Represented in JSON:

{"name":"孙悟空","age":18,"gender":"男"}

3. Features of AJAX

3.1 Advantages of AJAX

1) It is possible to communicate with the server side without refreshing the page.

2) Allows you to update part of the page content based on user events.

3.2 Disadvantages of AJAX

1) No browsing history, can't go back

2) There is a cross-domain problem (same origin)

3) Not SEO friendly

Experss framework established

experss.js build

//1. 引入express
const express = require('express');
const { request } = require('http');
//2. 创建应用对象
const app=express();

//3. 创建路由规则
// request 是对请求报文的封装
// response 是对响应报文的封装
app.get('/',(request,response)=>{
    //设置响应
    response.send('Hello express');
});
//4. 监听端口启动服务
app.listen(8000,()=>{
    console.log("服务已经启动,8000端口监听中......")
})

1. Enter the command " npm i experss " in the global file to create three files: node_modules, package-lock.json, and package.json.

2. Basically use .js in experss to input the command " node file name "

 3. Enter "127.0.0.1:8000" on the web page, where 8000 is the port set in the experss file.

4. Use of AJAX

4.1 Core Objects

XMLHttpRequest, all AJAX operations are performed through this object

4.2 Steps to use

1) Create an XMLHttpRequest object

       var xhr = new XMLHttpRequest();

2) Set request information

      xhr.open(method, url);

       //You can set the request header, generally not set

      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

3) Send request

     xhr.send(body) //Get requests do not pass body parameters, only post requests use

4) Receive the response

    //xhr.responseXML receives response data in xml format

    //xhr.responseText receives response data in text format

xhr.onreadystatechange = function (){

             if(xhr.readyState == 4 && xhr.status == 200){

             var text = xhr.responseText; console.log(text);

         }

}

1.GET

 GET.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <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>GET</button>
    <div id="result"></div>
    
</body>
<script>
  //获取button元素
  var bat=document.getElementsByTagName('button')[0];
 var result=document.getElementById('result');

   //绑定事件
   bat.onclick=function(){
       //1. 创建对象
       const xhr=new XMLHttpRequest();
       //2. 初始化 设置请求方法和 url
       xhr.open('GET','http://127.0.0.1:8000/server?a=100&b=200&c=300')
         //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){
                        //处理结果  行 头 空行 体
                        //响应 
                        // console.log(xhr.status);//状态码
                        // console.log(xhr.statusText);//状态字符串
                        // console.log(xhr.getAllResponseHeaders());//所有响应头
                        // console.log(xhr.response);//响应体
                        //设置 result 的文本
                        result.innerHTML = xhr.response;
                    }else{

                    }
                }
            }
   }
</script>
</html>

server.js

//1. 引入express
const express = require('express');

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

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

//4. 监听端口启动服务
app.listen(8000, () => {
    console.log("服务已经启动, 8000 端口监听中....");
});

result:

2.POST

POST.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>POST</title>
    <style>
        .result {
            width: 200px;
            height: 100px;
            border: 1px solid red;

        }
    </style>

</head>

<body>
    <button>POST</button>
    <div class="result"></div>
</body>
<script>
    const btn = document.getElementsByTagName('button')[0];
    const result = document.querySelector('.result');

    btn.onclick = function () {
        //1. 创建对象   
        const xhr = new XMLHttpRequest();
        //2. 初始化 设置类型与 URL
        xhr.open('POST', 'http://127.0.0.1:8000/posts');
        //设置请求头
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.setRequestHeader('name', 'atguigu');
        //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;
                } else {

                }
            }
        }
    }

</script>

</html>

server.js

//1. 引入express
const { response } = require('express');
const express = require('express');
const req = require('express/lib/request');

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

//3. 创建路由规则
// request 是对请求报文的封装
// response 是对响应报文的封装
 

app.all('/posts',(request,response)=>{
    //设置响应头  设置允许跨域
    response.setHeader('Access-Control-Allow-Origin', '*');
    //响应头
    response.setHeader('Access-Control-Allow-Headers', '*');

    response.end('Hello Ajax POST')
})



//4. 监听端口启动服务
app.listen(8000, () => {
    console.log("服务已经启动, 8000 端口监听中....");
});

result:

JSON

JSON.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX JSON 请求</title>
    <style>
        #result{
            width:200px;
            height:100px;
            border:solid 1px #90b;
        }
    </style>
</head>
<body>
    <button>JSON</button>
    <div id="result"></div>
    
</body>
<script>
  //获取button元素
  var bat=document.getElementsByTagName('button')[0];
 var result=document.getElementById('result');

   //绑定事件
   bat.onclick=function(){
       //1. 创建对象
       const xhr=new XMLHttpRequest();
          //设置响应体数据的类型
          xhr.responseType='json';
       //2. 初始化 设置请求方法和 url
       xhr.open('GET','http://127.0.0.1:8000/json-server')
         //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){
                        //处理结果  行 头 空行 体
                        //响应 
                        // console.log(xhr.status);//状态码
                        // console.log(xhr.statusText);//状态字符串
                        // console.log(xhr.getAllResponseHeaders());//所有响应头
                        // console.log(xhr.response);//响应体
                        //设置 result 的文本
                        console.log(xhr.response);
                        result.innerHTML = xhr.response.name;
                    }else{

                    }
                }
            }
   }
</script>
</html>

server.js

//1. 引入express
const { response } = require('express');
const express = require('express');
const req = require('express/lib/request');

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

//3. 创建路由规则
// request 是对请求报文的封装
// response 是对响应报文的封装

app.get('/json-server',(request,response)=>{
     //设置响应头  设置允许跨域
     response.setHeader('Access-Control-Allow-Origin','*');
         //响应头
    response.setHeader('Access-Control-Allow-Headers', '*');
     //响应一个数据
     const data={
         name:'atguigu'
     };
     //对对象进行字符串转换
     let str=JSON.stringify(data);
     //设置响应体
     response.send(str);
})



//4. 监听端口启动服务
app.listen(8000, () => {
    console.log("服务已经启动, 8000 端口监听中....");
});

result:

4.3 Solve IE cache

        Problem: In some browsers (IE), due to the existence of the caching mechanism, ajax will only send the first request, and the remaining multiple requests will not be sent to the browser but directly load the data in the cache.

        Solution: The browser's cache is recorded according to the url address, so we only need to modify the url address to avoid the cache problem

xhr.open("get","/testAJAX?t="+Date.now());

case:

Problem: Two browsers are opened at the same time. If the value reflected by the server is modified, the value displayed by the browser before the modification and the value displayed by the browser after the modification will appear. No synchronization will take place.

Solution: Add Date now(); on the request link

IE caching problem.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>IE 缓存问题.html</title>
    <style>
          .result{
            width:200px;
            height:100px;
            border:solid 1px #258;
        }
    </style>
</head>
<body>
    <button>IE 缓存</button>
    <div class="result"></div>
</body>
<script>
        const btn = document.getElementsByTagName('button')[0];
        const result = document.querySelector('.result');
        btn.addEventListener('click',function(){
            const xhr=new XMLHttpRequest();
            xhr.open("GET",'http://127.0.0.1:8000/ie?t='+Date.now());
            xhr.send();
            xhr.onreadystatechange = function(){
                if(xhr.readyState === 4){
                    if(xhr.status >= 200 && xhr.status< 300){
                        result.innerHTML = xhr.response;
                    }
                }
            }
        })

</script>
</html>

server.js

//1. 引入express
const { response } = require('express');
const express = require('express');
const req = require('express/lib/request');

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

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



//4. 监听端口启动服务
app.listen(8000, () => {
    console.log("服务已经启动, 8000 端口监听中....");
});

4.4 AJAX request status

xhr.readyState can be used to view the current state of the request

https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/readyState

0: Indicates that the XMLHttpRequest instance has been generated, but the open() method has not been called.

1: Indicates that the send() method has not been called, and setRequestHeader() can still be used to set the header information of the HTTP request.

2: Indicates that the send() method has been executed, and the header information and status code have been received.

3: Indicates that the data in the body part from the server is being received.

4: Indicates that the server data has been completely received, or this reception has failed

2. AJAX in jQuery

1. get request

$.get(url, [data], [callback], [type])

     url: URL address of the request.

     data: The parameters carried by the request.

     callback: callback function when loading is successful.

     type: Set the returned content format, xml, html, script, json, text, _default

2. post request

$.post(url, [data], [callback], [type])

     url: URL address of the request.

     data: The parameters carried by the request.

     callback: callback function when loading is successful.

     type: Set the returned content format, xml, html, script, json, text, _default.

3. Cross domain

1. JSON

1) What is JSONP

JSONP (JSON with Padding), is an unofficial cross-domain solution, developed purely with the ingenuity of programmers, and only supports get requests.

2) How does JSONP work?

Some tags on web pages are inherently capable of cross-domain, such as: img link iframe script. JSONP uses the cross-domain capabilities of script tags to send requests.

3) Use of JSONP

1. Dynamically create a script tag

var script = document.createElement("script");

2. Set the src of the script and set the callback function

script.src = "http://localhost:3000/testAJAX?callback=abc";

function abc(data) {

         alert(data.name);

};

3. Add the script to the body

document.body.appendChild(script);

4. Routing processing in the server

router.get("/testAJAX" , function (req , res) {

console.log("request received");

var callback = req.query.callback;

     var obj ={

       name: "Monkey King",

       age:18

     }

        res.send(callback+"("+JSON.stringify(obj)+")");

});

4) JSONP in jQuery

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

<body>
    <button id="btn">按钮</button>
    <ul id="list"></ul>
    <script type="text/javascript" src="./jquery-1.12.3.js"></script>
    <script type="text/javascript">
        window.onload = function () {
            var btn = document.getElementById('btn')
            btn.onclick = function () {
                $.getJSON("http://api.douban.com/v2/movie/in_theaters?callback=?", function
                    (data) {
                    console.log(data);
                    //获取所有的电影的条目
                    var subjects = data.subjects;
                    //遍历电影条目
                    for (var i = 0; i < subjects.length; i++) {
                        $("#list").append("<li>" +
                            subjects[i].title + "<br />" +
                            "<img src=\"" + subjects[i].images.large + "\" >" +
                            "</li>");
                    }
                });
            }
        }
    </script>
</body>

</html>

2. CORS

https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS

1) What is CORS?

CORS (Cross-Origin Resource Sharing), cross-domain resource sharing. CORS is an official cross-domain solution. Its feature is that it does not require any special operations on the client side, and it is completely processed in the server, and it supports get and post requests. The cross-origin resource sharing standard adds a new set of HTTP header fields, allowing the server to declare which origin sites have permission to access which resources through the browser

2) How does CORS work?

CORS tells the browser by setting a response header that the request allows cross-domain, and the browser will release the response after receiving the response.

3) Use of CORS

Mainly server-side settings:

router.get("/testAJAX" , function (req , res){

    //Set the response header through res to allow cross-domain requests

    //res.set("Access-Control-Allow-Origin","http://127.0.0.1:3000");

     res.set("Access-Control-Allow-Origin","*");

     res.send("Response returned by testAJAX");

});

1.node.js

2. nodemon automatic restart tool

Installation link:

https://www.npmjs.com/package/nodemon

Enter the command "npm install -g nodemon"

Enter the command "nodemon filename"

 Video: [Silicon Valley] 3 hours from getting started to mastering Ajax

This article is a self-summary of my learning video, please forgive me if there is any infringement. Infringement must be deleted.

Guess you like

Origin blog.csdn.net/QQ675396947/article/details/123953405