通过 FormData 获取表单数据 并发送Ajax请求

通过 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);

猜你喜欢

转载自blog.csdn.net/weixin_44129085/article/details/115254869