前端发送请求的方式

一、form表单提交

为了演示下面的案例,我们先用node.js写一个简易式服务器,用来接收前端发送过来的请求

//引用模块
const express = require('express');
创建对象
var app = express();

// post请求的两种解析方式
app.use(express.json());
app.use(express.urlencoded({
    
    extended:true}))
// 设置静态目录
app.use(express.static(__dirname+"/public"))
//get请求   定义了接口/login
app.get("/login",(req,res)=>{
    
    
    console.log();
    res.json({
    
    
        code:1000,
        msg:"get-成功",
        name:req.query.name,
        psw:req.query.psw
    })
})
//post请求
app.post("/register",(req,res)=>{
    
    
    console.log();
    res.json({
    
    
        code:1000,
        msg:"post-成功",
        name:req.body.name,
        psw:req.body.psw
    })
})
//监听服务端口
app.listen(8089,()=>{
    
    
    console.log("8089服务启动");
})

下面是一个form表单提交数据的案例

<form action="/login" method="get">
      <input type="text" name="name">
      <input type="text" name="psw">
      <input type="submit" value="get">
</form>
<form action="/register" method="post">
      <input type="text" name="name">
      <input type="text" name="psw">
      <input type="submit" value="post">
</form>

from表单把所有属于表单中的内容提交给后台,例如输入框,单选框,多选框,文本域,文件域等。

  1. form 标签是表单标签,在后台可通过对应的name属性获取相应的值。
  2. action 属性设置提交的服务器地址
  3. method 属性设置提交的方式 GET(默认值)或 POST

表单提交的时候,数据没有发送给服务器的三种情况:

  1. 表单项没有 name 属性值
  2. 单选、复选(下拉列表中的 option 标签)都需要添加 value 属性,以便发送给服务器
  3. 表单项不在提交的 form 标签中

表单提交特点:

  1. 每次提交都会刷新页面,无法做到局部刷新
  2. form表单提交会新建一个页面
  3. form表单是浏览器自带的,无论是否开启js,都可以提交表单。
  4. form表单的属性中有校验的字段,easyui,jeecg等都封装完成,用户只需添加正则表达式的校验规则。

为了演示

二、原生ajax

Ajax的全称是Asynchronous JavaScript and XML(即异步的JavaScript和XML),它并不是一种新的语言,二是几种原有技术的结合体。总体上来说,ajax是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术

<h1>原生ajax</h1>
<input type="text" id="userName">
<input type="text" id="pswd">
<button>原生---get</button>
<button>原生---post</button>
<script>
    let getBtn = document.querySelectorAll('button')[0];
    let postBtn = document.querySelectorAll('button')[1];

    // 原生ajax-get
    getBtn.onclick = function () {
     
     
        // 1.创建请求对象

        let xhr = new XMLHttpRequest();
        // 2.创立链接
        xhr.open("get", `/login?name=${
       
       userName.value}&psw=${
       
       pswd.value}`, true)
        // 3.发送请求
        // xhr.setRequestHeader("Content-Type","applacation/json")
        // xhr.setRequestHeader("Content-Type","applacation/x-www-form-urlencoded")
        xhr.send();
        // 监听请求状态
        xhr.onreadystatechange = function () {
     
     
            if (xhr.readyState == 4 && xhr.status == 200) {
     
     
                console.log("ajax-get", xhr.responseText);
            }
        }
    }
    // 原生ajax-post
    postBtn.onclick = function () {
     
     
        // 1.创建请求对象

        let xhr = new XMLHttpRequest();
        // 2.创立链接
        xhr.open("post", "/register", true)
        // 3.发送请求
        xhr.send(`name=${
       
       userName.value}&psw=${
       
       pswd.value}`);
        // 监听请求状态
        xhr.onreadystatechange = function () {
     
     
            if (xhr.readyState == 4 && xhr.status == 200) {
     
     
                console.log("ajax-post", xhr.responseText);
            }
        }
</script>

ajax请求的整个过程我们可以用下面一个小例子进行对比

整个交互流程 我们用打电话流程比喻

  1. 先有手机 js里面功能性先找对象 比如 日期相关 Date 数学Math,ajax就找XMLHttpRequest
  2. 有信号 数据网
  3. 手机输入号码 点击拨号键
  4. 监听电话是否通畅 有 信号 无法接通 欠费了 对方忙,无人接听

ajax请求的优点

  1. 通过异步模式,提升了用户体验-------ajax在提交、请求、接收时,是异步进行的,不影响页面其他部分
  2. 优化了浏览器和服务器之间的传输,减少不必要的数据往返,减少了带宽占用。
  3. ajax引擎在客户端运行,承担了一部分本来由服务器承担的工作,从而减少了大用户量下的服务加载。

ajax请求的缺点

  1. ajax必须要用js来实现,存在调试麻烦、浏览器兼容问题,而且不启用js的浏览器,无法完成操作。
  2. 不支持浏览器back按钮
  3. ajax暴露了与服务器交互的细节
  4. 对搜索引擎支持较弱

三、jQuery的ajax

jQuery的ajax参数

type:请求方式
url:请求地址(后台数据接口)
data: 规定要发送到服务器的数据。
dataType:服务器响应的数据类型。
success(result,status,xhr):成功时的回调函数
更多的参数,可以去查阅菜鸟教程或者W3C

<h1>jQuery--ajax</h1>
<input type="text" id="userName">
<input type="text" id="pswd">
<button class="jqGet">jQ---get</button>
<button class="jqPost">jQ---post</button>
<!-- 这里要注意下你要引用的jQuery路径 -->
<script src="./jquery.min.js"></script>
<script>
// *****************jQ-get
    $('.jqGet').click(() => {
     
     
        $.ajax({
     
     
            type: "get",
            url: "/login",
            data: {
     
      name: userName.value, psw: pswd.value },
            // 注意这里是写数据类型,这里要么不写,要么写json
            dataType: "dataType",
            success: function (response) {
     
     
                console.log("jQ-get:", response);
            }
        });
    })
// *****************jQpost
    $('.jqPost').click(() => {
     
     
        $.ajax({
     
     
            type: "post",
            url: "/register",
            data: {
     
      name: userName.value, psw: pswd.value },
            success: function (response) {
     
     
                console.log("jQ-post:", response);
            }
        });
    })
</script>

四、axios

Vue2.0之后,尤雨溪推荐大家用axios替换JQuery ajax,想必让axios进入了很多人的目光中。
axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,本质上也是对原生XHR的封装,只不过它是Promise的实现版本,符合最新的ES规范,它本身具有以下特征:

1.同时支持浏览器端和服务端的请求。
2.支持 Promise API
3.支持请求和和数据返回的拦截客户端
4.提供了一些并发请求的接口(重要,方便了很多的操作)
5.取消请求
6.转换请求返回数据,自动转换JSON数据
7.支持防止CSRF
注意:防止CSRF:就是让你的每个请求都带一个从cookie中拿到的key, 根据浏览器同源策略,假冒的网站是拿不到你cookie中得key的,这样,后台就可以轻松辨别出这个请求是否是用户在假冒网站上的误导输入,从而采取正确的策略。

<h1>axios--ajax</h1>
<input type="text" id="userName">
<input type="text" id="pswd">
<button class="aGet">jQ---get</button>
<button class="aPost">jQ---post</button>
<!-- 这里要注意下你要引用的jQuery路径和axios路径 -->
<script src="./jquery.min.js"></script>
<script src="./axios.min.js"></script>
<script>
    // *****************axios-get
    $(".aGet").click(() => {
     
     
        axios.get("/login", {
     
     
            params: {
     
      name: userName.value, psw: pswd.value }
        }).then((response) => {
     
     
            // then就相当于success
            console.log("axios-get", response);
        })
    })
    // *****************axios-post
    $(".aPost").click(() => {
     
     
        // post请求  参数直接写{}   不需要外面那层params
        axios.post("/register", {
     
      
            name: userName.value, psw: pswd.value 
        }).then((response) => {
     
     
            // then就相当于success
            console.log("axios-post", response);
        })
    })
</script>

五、fetch

fetch号称是AJAX的替代品,是在ES6出现的,使用了ES6中的promise对象。Fetch是基于promise设计的。Fetch的代码结构比起ajax简单多了,参数有点像jQuery ajax。但是,一定记住fetch不是ajax的进一步封装,而是原生js,没有使用XMLHttpRequest对象。
fetch的优点:
1.符合关注分离,没有将输入、输出和用事件来跟踪的状态混杂在一个对象里
2.更好更方便的写法

文章结尾给大家附上ajax请求的五种状态

0 - (未初始化)还没有调用send()方法
1 - (载入)已调用send()方法,正在发送请求
2 - (载入完成)send()方法执行完成,已经接收到全部响应内容
3 - (交互)正在解析响应内容
4 - (完成)响应内容解析完成,可以在客户端调用了

猜你喜欢

转载自blog.csdn.net/m0_56026872/article/details/118310656
今日推荐