Ajax(异步的js和xml)

本文介绍了前端如何通过XMLHttpRequest进行JSON响应处理,包括设置响应体类型、发起GET请求、处理服务器返回的数据。同时,讲解了HTTP协议的基本概念,展示了Express框架创建路由和响应的方法,以及AjaxGET请求的实现。此外,还讨论了如何取消Ajax请求和处理超时问题。
摘要由CSDN通过智能技术生成

1.JSON响应

前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>3JSON 请求</title>
    <style>
        .result{
            width: 200px;
            height: 100px;
            border: 1px solid darkred;
        }

    </style>
</head>
<body>
    <div class="result"></div>

    <script>
        //获取元素
        let result = document.querySelector('.result');
        // 键盘按下事件(注意这里绑定的是Window事件)
        window.addEventListener('keydown',function () {
            //1.创建对象
            let xhr = new XMLHttpRequest();

            // 设置响应体数据类型
            xhr.responseType = 'json'

            //2.open初始化
            xhr.open('GET','http://localhost:8000/server-json')
            //3.发送
            xhr.send()
            //4.绑定事件
            xhr.onreadystatechange = function () {
                if (xhr.readyState===4){
                    if (xhr.status>=200 && xhr.status<300){
                        //1. 手动解析 JSON
                        /*let data = JSON.parse(xhr.response);
                        console.log(data)
                        result.innerHTML = data.name;*/

                        //自动解析json
                        console.log(xhr.response)
                        result.innerHTML = xhr.response.name;
                    }
                }
            }
        })
    </script>
</body>
</html>

服务器代码

//1.引入 express
const express = require('express')
//2.创建应用对象
const app = express();
//3.创建路由规则
app.get('/server',(request,response)=>{
    //设置响应头,允许跨域
    response.setHeader('Access-control-Allow-Origin','*')
    //设置响应
    response.send('HELLO AJAX GET')
})

app.post('/server',(request,response)=>{
    //设置响应头,允许跨域
    response.setHeader('Access-control-Allow-Origin','*')
    //设置响应
    response.send('HELLO AJAX POST')
})

//响应json
app.get('/server-json',(request,response)=>{
    //设置响应头,允许跨域
    response.setHeader('Access-control-Allow-Origin','*')
    let obj1 = {
        name:'余敏',
        age:88
    }
    let str = JSON.stringify(obj1);
    //设置响应
    response.send(str)
})


//4.监听端口,启动服务
app.listen(8000,()=>{
    console.log('服务器已启动,正在监听8000端口......')
})

2.http协议

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

请求报文

行      POST  /s?ie=utf-8  HTTP/1.1 
头      Host: baidu.com
        Cookie: name=baidu
        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>一级标题</h1>
            </body>
        </html>

 3.express的基本使用(express就是一个模拟后端的工具)

//1.引入express
const express = require('express')
//2.创建应用对象
const app = express();
//3.创建路由规则
app.get('/',(request,response)=>{
    response.send('hello ajax')
})
//4.监听端口启动服务
app.listen(8000,()=>{
    console.log('8000端口号已经启动')    
})

4.ajax之get请求

前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>01 GET 请求</title>
  <style>
    .result{
      width: 220px;
      height: 100px;
      border: 1px solid red ;
    }
  </style>
</head>
<body>
  <button>获取get请求</button>
  <div class="result"></div>

  <script>
    let btn01 = document.querySelector('button');
    let result = document.querySelector('.result')
    //绑定事件
    btn01.addEventListener('click',function () {
      //1.创建对象
      let xhr = new XMLHttpRequest();
      //2.初始化吗,设置请求方法和url
      xhr.open('get','http://localhost:8000/server')
      //3.发送
      xhr.send()
      //4.绑定事件,处理服务端返回结果
      //on when当...时候
      //readystate是xhr对象中的属性,表示状态0 1 2 3 4
      //change改变
      xhr.onreadystatechange=function () {
        //判断(服务器返回了所有的结果)
        if (xhr.readyState===4){
          //判断响应码 200-300之间是成功响应码
          if (xhr.status>=200 && xhr.status<300){
            console.log(xhr.getAllResponseHeaders())//获取所有响应头
            console.log(xhr.status);//状态码
            console.log(xhr.response);//响应体
            //设置result的文本
            result.innerHTML = xhr.response;
          }
        }
      }

    })
  </script>
</body>
</html>

后端代码:

//1.引入express
const express = require('express')
//2.创建应用对象
const app = express()
//3.创建路由规则
app.get('/server',(request,response)=>{
    //设置响应头,允许跨域
    response.setHeader('Access-control-Allow-Origin','*')
    response.send('hello express')
})

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

5.取消请求

前端代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>取消请求</title>
</head>
<body>
    <button>发送请求</button>
    <button>取消请求</button>
<script>
    let btns = document.querySelectorAll('button')
    let x = null;
    btns[0].addEventListener('click', function () {
        x = new XMLHttpRequest();
        x.open('GET','http://127.0.0.1:8000/delay')
        x.send()
    })
    //取消请求
    btns[1].addEventListener('click', function () {
        x.abort();//XMLHttpRequest中的abort()方法
    })

</script>
</body>
</html>

后端代码:

// 超时
app.get('/delay',(request,response)=>{
    //设置响应头,允许跨域
    response.setHeader('Access-control-Allow-Origin','*')
    //设置响应
    setTimeout(function () {
        response.send('延迟响应')
    },3000)
})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值