目标:ajax发送请求传参的常见方式
说明:归纳了常见且简单的书写方式、排除原始js使用"+"拼接的方式
种类:2+1
实例
方式一:使用对象形式{}
使用场景:所有js
形式:data:{uname:"tom",relation:"brother"}
ajax({
type:...,
url:...,
data:{uname:"tom",relation:"brother"},
dataType:json
}).then()
或
$.ajax({
type:...,
url:...,
data:{uname:"tom",relation:"brother"},
success:(data)=>{
consooe.log(data);
},
error:()=>{
alert("系统维护中、请稍后");
}
})
方式二:使用转义字符··
使用场景:所有js
形式:data:`uname="tom"&relation="brother"`
实例:
ajax({
type:...,
url:...,
data:`uname="tom"&relation="brother"`,
dataType:json
}).then()
或
$.ajax({
type:...,
url:...,
data:`uname="tom"&relation="brother"`,
success:(data)=>{
consooe.log(data);
},
error:()=>{
alert("系统维护中、请稍后");
}
})
方式三:表单(序列化表单)提交函数serialize();
使用场景:jQuery
形式:data:$("#form").serialize();
注意:表单元素必须保证name名称为真(true)
深度剖析:序列化表单实际就是将name名称和值作为键值对传参
代码:
<form action="" method="" id="form">
<input value="tom" name="uname">
<input value="brother" name="relation">
</form>
序列化表单/*$("#form")serialize()*/:
uname="tom"&relation="brother"
实例:
$.ajax({
type:...,
url:...,
data:$("#form").serialize(),
success:(data)=>{
consooe.log(data);
},
error:()=>{
alert("系统维护中、请稍后");
}
})