ajax、fetch、axios用法

一、ajax

1、jquery ajax 语法模板

    $.ajax 
    $.get
    $.post
    $.put
    $.delete
    $.load 
    $.ajax({
        url,
        timeout,  // 超时
        beforeSend,  // 发送之前 
        dataType, // 返回数据格式 
        type,   // 请求方式 
        data,   // 参数
        headers,  // 请求头 
        success,  // 请求成功
        fail,    // 请求失败
        complete    // 请求结束 
    })

2、ajax post请求

$.ajax({
     url:url,
     type:"POST",
     data:this.userinfo,  
     success(res){
        console.log(res);
     }
})

3、ajax get请求

$.ajax({
     url:"http://localhost:3000/vue",
     success(res){
          console.log(res);
     }
})

二、fetch用法

1、fetch 请求数据

fetch 抓取数据  不需要引入 直接调用
   1. 第一个参数是URL 
   2. 第二个参数是可选参数 (data headers)
   3. 使用了 JavaScript Promises 来处理结果/回调:(then 成功的回调 )  (catch 失败的回调 )

2、fetch 写法 固定

    fetch(url,options)
    .then(res=>res.json())   // 转为json 格式
    .then(result=>result)    // 成功的回调
    .catch(err=>err)

3、POST 提交三种比较重要的 content-type

    1    'Content-Type': 'application/json'   服务端消息主体是序列化的JSON字符串  除IE 外都支持 
    2    'Content-Type': 'application/x-www-form-urlencoded'   发送到服务器之前,所有字符都会进行编码
    提交的数据按照 key1=val1&key2=val2 的方式进行编码,key 和 value 都进行了 URL 转码
    var obj = {username:"zkl"}  username=zkl
    3    'Content-Type': 'multipart/form-data'       不对字符编码。在使用包含文件上传控件的表单时,必须使用该值

4、fetch post请求代码

fetch(url,{
      method:"POST",   // POST 请求 
      headers:{   // 请求头 
            'Content-Type': 'application/json'   // 传递 JSON 字符串 
      },
      body:JSON.stringify(this.userinfo)
   })
   .then(res=>res.json())
   .then(res=>{
         console.log(res)
   })

5、fetch get请求代码

fetch(url) 
     .then(res=>res.json())   // 变为json 数据
     .then(res=>console.log(res))
     .catch(err=>console.log(err))

三、axios方法

1、axios 语法模板

基于 Promise    .then().catch()
axios.get(url[, config])
axios.post(url[, data[, config]])
axios({
   url, 
   method,  // 请求方式
   headers,  // 请求头 
   baseURL,  // 接口域名   http://localhost:3000/
   data,    //  post 请求提交的 数据   
   params ,   //  传递查询参数search  ?limit=8
   timeout,  // 超时 
}).then(result)
.catch(err)

2、axios get请求

axios.get("https://m.maizuo.com/gateway?cityId=440300&ticketFlag=1&k=3548401",{
          params:{}
      })
     .then(res=>{
         console.log(res);   // 渲染数据到 vue 里面
      })

3、axios post请求

axios({
      url:url,
      method:"POST",  // POST 请求 
      data:data,   // POST 请求提交的参数 
      }).then(res=>{
          console.log(res);
          console.log(res.data.msg)
      })
posted @ 2020-07-24 20:15  飘逸_winxin  阅读(243)  评论(0编辑  收藏  举报