Ajax form Asynchronous upload file instance code detailed

Source: Internet
Author: User
This article mainly introduces the Ajax form asynchronous upload file instance code (including file field), very good, with reference value, interested friends to see together, hope to help everyone.

1. Causes

When you do the foreground page, you need to call Webapi's POST request, send some fields and files (equivalent to send the form asynchronously through Ajax to get the results returned), and then get the return value to determine whether the success.

2. Try

First try a "jQuery Form Plugin", this thing is a huge pit, to achieve his and jquery1.9.2 compatibility is not too good, finally to solve the problem of $.browser, found that using his upload file can not get the return value.

$ ("#view"). Submit ($ ("#view"). Ajaxsubmit ({type: "post", url: "). /api/article/add ", DataType:" JSON ", Success:function (msg) {Console.log (msg);},error:function (msg) {$ (" #resultBox ") . HTML ("Connection Server failed"); Console.log (msg);}));

For example, the above code, but how to configure, as long as the file is uploaded, success inside the returned MSG must be null (Chromium browser), but actually there is a return value, and there is no file is normal. More frightening is the Ie/edge under the prompt to download the JSON return value.

Turn over the source code of Jquery.form.js, found that he is using IFRAME implementation of pseudo-Ajax, not halal, pass!

Is there files to upload?var files = $ (' input:file ', this). Fieldvalue (); var found = False;for (var j=0; J < FILES.L Ength; J + +) if (files[j]) found = true;if (Options.iframe | | found)//Options.iframe allows user to force IFrame modefileupload () ; Else$.ajax (options);

This is when there are no files, call 2 different functions respectively.

3. Solution

After many anti-investigation, found that XHR (XMLHttpRequest) is a good thing. Tested mainstream browsers and mobile browsers support this stuff. Here's how to get the native XMLHttpRequest object upload form (file) in Jquery/zepto Ajax. Reference article: http://www.jb51.net/article/91267.htm

function Ajaxform (FormID, options) {var form = $ (FormID);//Direct the Form object as a parameter new FormData object var formData = new FormData (form[0] ); $ ("input[type= ' file ']"). ForEach (function (item, i) {//Get the file object is equivalent to the $_files data that can be directly post var Domfile = $ (item) [0].files [0];//Append file Object formdata.append (' file ', domfile);}) if (!options) options = {};options.url = Options.url? options.url:form.attr ("Action"); Options.type = Options.type? opti Ons.type:form.attr ("method"); Options.data = Formdata;options.processdata = false; Tell JQuery is not to process the Dataoptions.contenttype = false; Tell JQuery isn't to set contenttypeoptions.xhr = OPTIONS.XHR? Options.xhr:function () {///This is the key to get the native XHR object to do all the things previously done var xhr = $.ajaxsettings.xhr (); xhr.upload.onload = function () {cons Ole.log ("onload");} xhr.upload.onprogress = function (EV) {if (ev.lengthcomputable) {var percent = + * Ev.loaded/ev.total;console.log (perc ENT, Ev)}}return Xhr;};o Ptions.success = options.success? Options.success:function (data) {alert (data)};$.aJax (options);} Call $ ("#sub"). Click (function (e) {ajaxform ("#myForm");});

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.