Use the FormData object of html5 to asynchronously submit file data through the Ajax form

伊谢尔伦
Release: 2016-12-10 09:28:49
Original
1923 people have browsed it

Every time you submit file object data to the server, you always need to use various third-party plug-ins to implement the form asynchronous submission function, and you also need to customize different plug-in css for different interfaces, which is quite cumbersome. XMLHttpRequest Level 2 adds a new interface - FormData. Using the FormData object, we can use some key-value pairs to simulate a series of form controls through JavaScript. We can also use the send() method of XMLHttpRequest to submit the form asynchronously. Compared with ordinary Ajax, the biggest advantage of using FormData is that we can upload binary files asynchronously.
Without further ado, let’s get straight to the code:

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('连接超时');
        }
    }
};
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!