Home > Article > Web Front-end > Use the FormData object of html5 to asynchronously submit file data through the Ajax form
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('连接超时'); } } };