通过 FormData 获取表单数据 并发送Ajax请求
作者:Bright Xu
样例表单
<form action="/user/login" method="post">
<input name="username">
<input type="password" name="password">
<button type="submit">登录</button>
<button type="reset">重置</button>
</form>
以FormData
原生格式上传
$("form").submit((e)=>{
let form = e.target;
let formData = new FormData(form);
$.ajax({
url: form.action,
data: formData,
type: "POST",
processData: false,
contentType: false,
success: function (result) {
console.log(result);
}
})
return false;
})
以JSON
的格式提交,注意不能提交图片等文件数据
$("form").submit((e)=>{
let form = e.target;
let formData = new FormData(form);
let data = {
};
formData.forEach((v, k)=>{
data[k] = v;
})
$.ajax({
url: form.action,
data,
type: "POST",
success: function (result) {
console.log(result);
}
})
return false;
})
图片 获取 base64
let img = $(":file")[0].files[0];
let fr = new FileReader();
let bs;
fr.onload = (e) => {
bs = e.target.result;
}
fr.readAsDataURL(img);
console.log(bs);