Ajax form Asynchronous upload file instance code (including file domain) _ajax related

Source: Internet
Author: User
Tags json

1. Causes

When you do the front page, you need to call the WEBAPI POST request, send some fields and files (equivalent to sending the form asynchronously via Ajax, get the return result), and then get the return value to determine if it's successful.

2. Try

First tried "JQuery Form Plugin", this thing is a huge pit, to achieve his and jquery1.9.2 compatibility is not too good, not easy to solve the problem of $.browser, found that with 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 uploaded files, success The return of MSG must be null (Chromium browser), but the actual return value, and there is no file is normal. What is more frightening is that Ie/edge is prompted to download the JSON return value.

Turn over the source code of Jquery.form.js, found that he is implemented with an IFRAME pseudo Ajax, not halal, pass!

Are there files to upload?
var files = $ (' input:file ', this). Fieldvalue ();
var found = false;
For (Var j=0 j < Files.length; J + +)
if (Files[j]) 
found = true;
if (Options.iframe | | found)//Options.iframe allows user to force iframe mode
fileupload ();
else
$.ajax (options);

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

3. The solution

After much investigation, XHR (XMLHttpRequest) was found to be a good thing. After testing the mainstream browser and mobile browser support this thing. 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);//Convert Form object directly as parameter new FormData object var formData = new FormData (for
M[0]); $ ("input[type= ' file ')"). ForEach (function (item, i) {//Get the file object that is equivalent to the $_files data var domfile = $ (item) that can be directly post [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?
Options.type:form.attr ("method");
Options.data = FormData; Options.processdata = false; Tell JQuery isn't to process the data Options.contenttype = false; Tell JQuery isn't to set contentType OPTIONS.XHR = options.xhr?
Options.xhr:function () {//This is the key to get the native XHR object do all the things previously done var xhr = $.ajaxsettings.xhr (); xhr.upload.onload = function () {
Console.log ("onload"); } xhr.upload.onprogress = function (EV) {if (ev.lengthcomputable) {var percent = MB * EV.LOADED/EV.TOTAL; console.log
(Percent, Ev)}
return XHR;
}; Options.success = options.success? Options.success:fuNction (data) {alert (data)};
$.ajax (options); //Call $ ("#sub"). Click (function (e) {ajaxform ("#myForm");});

The above is a small set to introduce the Ajax form asynchronous upload file instance code (including file domain), I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Related Article

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.