Jquery ajax 传参

Yunxiao 2022年07月29日 672次浏览

前言

因为工作需要用到juqery的Ajax来调用后端接口,由于之前根本没写过前端,所以对传参这块也很模糊,故专门梳理了一下常用的传参方法
首先放一个jquery Ajax的官网doc

ajax请求格式

在Jquery中Ajax有两种请求格式,一种简写,一种完整的

//简单的
//没有data是可以省略不传
$.get/post(url,data,function(res){
   //处理返回结果
})
//完整的
$.ajax({
type:'get/post',
url: 'url',
data: data
dataType: 'xxx'
contentType: 'xxxx'
... 其他设置项
success: function(res){
//处理成功回调
}
error:function(res){
//处理错误回调
}
})

其中应该只有url是必填的,其他的设置都有默认的缺省值

URL地址传参

Get请求的参数一般都是放在地址后面,以 param = xxx的形式出现,Jq中的get、post方法会自动帮你拼装你传递的data参数
例如我们定义参数

 let parms = {
     'parm1': 'parm1',
     'parm2':2,
     "parm3":'parm3',
 }

在ajax方法中指定data: parms 即可,无需去链接上手动拼接参数

Body传参

当后端接口需要在body中接收参数时,例如在JAVA后端使用@RequestBody来接收参数,现在前后端一般都使用JSON来进行交互,所以一般data的类型也是json.则我们在传递data时需要使用诸如JSON.stringify(parms)来传参
同时还需要指定dataType 和 contentType这两个参数,例如

 data: JSON.stringify(params),
 dataType: "json",
 contentType: "application/json;charset=utf-8",

这样Jq就会把参数放在请求的Body里面,后端也就可以正常接收了

文件传参

这个相对比较特殊,比如我们使用html原生的input接受到一个文件,需要传递到后端
首先我们需要获取到上传的文件,直接用代码举例把,前端的内容我也不太擅长描述

//html
<input type="file" @change="uploadFile(index,1)" ref="fileCover">
//js
this.Images = this.$refs.fileCover.files[0]
const formData = new FormData();
formData.append('file', this.Images);

这样,formData就是我们要传递的参数了
然后Jq中参数需要

type: "post",
data: formData,
contentType: false, //不设置内容类型
processData: false, //不处理数据

比较特殊的就是contentType需要和processData需要设置为false
即不在请求头中指定contentType
关于peocessData

Type: Boolean
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type “application/x-www-form-urlencoded”. If you want to send a DOMDocument, or other non-processed data, set this option to false.

大意就是默认情况下Jq会把你传递的data处理成一个query string。 当你需要传递文件或者任何其他不需要处理的data时,将processData设置为false即可