使用HTML5的FormData对象, 通过 Ajax表单异步提交文件数据

每次在向服务器提交文件对象数据是,总是需要借助各种三方插件来实现表单异步提交功能,还要为不同的界面去定制不同的插件css,相当繁琐。XMLHttpRequest Level 2 添加了一个新的接口——FormData。利用 FormData 对象,我们可以通过 JavaScript 用一些键值对来模拟一系列表单控件,我们还可以使用 XMLHttpRequest 的 send() 方法来异步的提交表单。与普通的 Ajax 相比,使用 FormData 的最大优点就是我们可以异步上传二进制文件。
话不多说直接上代码:

var formData = new FormData();
formData.append('template', that.template);
formData.append('declare', that.declareData.declare);
formData.append('self_intro', that.declareData.self_intro);
formData.append('plan_name', that.declareData.plan_name);
//$("#business_plan") 是一个file类型的input对象
formData.append('business_plan', $("#business_plan")[0].files[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);

xhr.setRequestHeader("Accept", "application/json");
xhr.send(formData);
// 指定通信过程中状态改变时的回调函数
xhr.onreadystatechange = function () {
    // 通信成功时,状态值为4
    var completed = 4;
    if (xhr.readyState === completed) {
        if (xhr.status === 200) {
            // 处理服务器发送过来的数据
            var result = JSON.parse(xhr.responseText);
            //这里你可以随意的处理这个result对象了
            //...
        } else {// 处理错误
            alert('连接超时');
        }
    }
};

猜你喜欢

转载自www.cnblogs.com/jlfw/p/12956320.html
今日推荐