ajax、fetch、axios使用方法

  1. jquery ajax 来请求数据

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

    使用方法,先引入jq文件,再使用$.ajax

 $.ajax({
   url:"接口地址",
    type:"POST/get",
    data:this.userinfo,  
    success(res){
        console.log(res);
    }
})
  1. fetch是浏览器的内置方法,不需要引入文件,直接使用

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

//fetch 写法 固定

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

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’ 不对字符编码。在使用包含文件上传控件的表单时,必须使用该值

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)
   })

	fetch("url") 				//规范格式
   .then(res=>res.json())   	// 变为json 数据
   .then(res=>console.log(res))
   .catch(err=>console.log(err))

  1. axios基于 Promise .then().catch()

    axios({
        url, 
        method,  // 请求方式
        headers,  // 请求头 
        baseURL,  // 接口域名   http://localhost:3000/
        data,    //  post 请求提交的 数据   
        params ,   //  传递查询参数search  ?limit=8
        timeout,  // 超时 
    }).then(result)
    .catch(err)
    
 axios({
       url:"接口地址",
        method:"GET"			//方法类型
    }).then(res=>{				//成功的回调
        console.log(res)
    }).catch(err=>{				//失败的回调
        console.log(err)
    })

猜你喜欢

转载自blog.csdn.net/qq_40375518/article/details/107567585
今日推荐