Ajax的使用

AJAX

1.介绍

1.AJAX 的使用

在 js 中有内置的构造函数来创建 ajax 对象

创建 ajax 对象以后,我们就使⽤ ajax 对象的⽅法去发送请求和接受响应

Ajax的一个最大的特点是无需刷新页面便可向服务器传输或读写数据(又称无刷新更新页面),这一特点主要得益于XMLHTTP组件

XMLHTTPRequest对象

2.express

在学习Ajax中我们用到express框架,我们先引入express

npm init --yes
npm -i express

设置完成后我们引入express,并且创建express对象

/* 引入express */
const express = require('express');
/* 创建对象 */
const app = express();

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

/* 监听端口启动服务 */
app.listen(8030,()=>{
    console.log("服务启动");
})

3.Ajax

const btn = document.querySelector("button");
const result = document.querySelector(".box");
btn.addEventListener("click",function(){
    /* 创建对象 */
    const xhr = new XMLHttpRequest()
    /* 初始化 设置请求方法和url */
    xhr.open('GET',"http://localhost:8030/serve");
    /* 发送  */
    xhr.send();
    /* 事件绑定 */
    xhr.addEventListener("readystatechange",function(){
        if (xhr.readyState === 4)
        {
            if (xhr.status >= 200 && xhr.status < 300){
                /*                     console.log(xhr.status);
                    console.log(xhr.statusText); */
                result.innerHTML=xhr.response;
            }else {

            }
        }
    })

4.ajax 状态码 - xhr.readyState

ajax 状态码 - xhr.readyState

readyState === 0 : 表示未初始化完成,也就是 open 方法还没有执行

readyState === 1 : 表示配置信息已经完成,也就是执行完 open 之后

readyState === 2 : 表示 send 方法已经执行完成

readyState === 3 : 表示正在解析响应内容

readyState === 4 : 表示响应内容已经解析完毕,可以在客户端使用

在当===4时我们使用服务端给我们的数据

5.readyStateChange事件

这个事件是专⻔用来监听 ajax 对象的 readyState 值改变的的行为

也就是说只要 readyState 的值发生变化了,那么就会触发该事件

所以我们就在这个事件中来监听 ajax 的 readyState 是不是 4

6.GET设置请求参数

xhr.open('GET',"http://localhost:8030/serve?a=100&b=200");

7.AJAXPost请求

const div =document.querySelector("div");

div.addEventListener("mousemove",function(){
    const xhr = new XMLHttpRequest();
    xhr.open('POST',"http://localhost:8030/serve");
    xhr.send();

    xhr.addEventListener("readystatechange",function(){
        if (xhr.readyState === 4){
            if (xhr.status >= 200 && xhr.status <300){
                div.innerHTML=xhr.responseText;
            }else{

            }
        }
    })
})

在serve.js中给post

app.post("/serve",(request,response)=>{
    /* 设置响应头 设置允许跨域访问 */
    response.setHeader('Access-Control-Allow-Origin','*');
    /* 设置响应体 */
    response.send("Hello AJAX POST");
})

7.POST设置请求参数

xhr.send("a=100&b=200&c=300");

xhr.send('a:100&b:200&c:300');

8.设置请求头信息

xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
response.setHeader('Access-Control-Allow-Headers','*')

9.接收JSON

<div class="box"></div>
<script>
    const div = document.querySelector(".box");
window.addEventListener("keydown",function(){
    const xhr = new XMLHttpRequest();

    xhr.open("POST","http://localhost:8030/serve");
    xhr.send();
    xhr.addEventListener("readystatechange",function(){
        if (xhr.readyState===4){
            if (xhr.status >=200 && xhr.status <300){
                /* 手动转换 */
                const data = JSON.parse(xhr.responseText);
                div.innerHTML=data.name;
                /* 自动转换 */
                console.log(xhr.response);
                div.innerHTML=xhr.response
            }else{

            }
        }
    })
})
app.all("/serve",(request,response)=>{
    /* 设置响应头 设置允许跨域访问 */
    response.setHeader('Access-Control-Allow-Origin','*');
    //响应头
    response.setHeader('Access-Control-Allow-Headers','*')
    /* 设置响应体 */
    const data = {
        name:"ikun"
    }
    let str = JSON.stringify(data);
    response.send(str);
})

10.nodemon自动重启

由于之前每次修改serve.js都要重新启动,所以我们使用nodemon

npm install -g nodemon
nodemon serve.js
//如果报错
npx nodemon serve.js

11.解决IE缓存问题

xhr.open("POST","http://localhost:8030/serve?t="+Date.now());

2.AJAX请求

1.请求超时和网络异常处理

const div = document.querySelector(".box");
window.addEventListener("keydown",function(){
    const xhr = new XMLHttpRequest();

    xhr.open("POST","http://localhost:8030/delay");
    xhr.send();
    
    
    xhr.timeout=2000;

    xhr.addEventListener("timeout",function(){
        alert("网络异常");
    })
    xhr.addEventListener("error",function(){
        alert("网络断开连接");
    })
    
    
    xhr.addEventListener("readystatechange",function(){
        if (xhr.readyState===4){
            if (xhr.status >=200 && xhr.status <300){
                div.innerHTML=xhr.response;
            }else{

            }
        }
    })
})

2.取消请求

xhr.abort();

3.解决重复请求

const btn1 = document.querySelector(".send");
const btn2 = document.querySelector(".done");
let x=null;
let isSending=false;
btn1.addEventListener("click",function(){
    if (isSending) x.abort();
    x= new XMLHttpRequest();    
    x.open("GET","http://177.0.0.1:8000/delay");
    x.send();
    isSending=true;
    x.addEventListener("readystatechange",function(){
        if (x.readyState==4){
            isSending=4;
        }
    })
})
btn2.addEventListener('click',function(){
    x.abort();
})

4.Jquery发送请求

$.ajax({
    url: '', 
    data: {	
        name: 'zs',
        adress: 'ss'
    },
    type: 'get',		
    dataType: 'text',	
    success: function (res) { 
        $('#get1').html(res)
    },
    error: function (xhr, errorMessage, e) {
        alert(errorMessage);
    }
})

5.Axios发送请求

axios({
//    请求方法:
 method:'POST',
 //    请求地址
 url:'/axios-server',
 // 参数
params:{},
// 请求头
headers:{},
// 请求体
data:{}
}).then()

3.同源策略

1.介绍

浏览器的一种安全策略

同源:协议、域名、端口号,必须完全相同

2.cors中间件

1.npm i cors

2.const cors = require(“cors”)

3.app.use(cors)

由一系列HTTP响应头组成

在服务端进行配置,不需要做额外配置

在浏览器中有兼容性

const express = require("express");
const cors = require("cors");
const app = express();

app.use(cors());

app.all('/',(req,res)=>{
    res.send("a");
})

app.listen(4400,()=>{
    console.log("启动");
})
  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值