Home Web Front-end JS Tutorial Ajax operation form asynchronously uploads files

Ajax operation form asynchronously uploads files

Apr 03, 2018 pm 03:43 PM
ajax upload asynchronous

This time I will bring you an Ajax operation form to upload files asynchronously. What are the precautions for Ajax operation form to asynchronously upload files? The following is a practical case, let's take a look.

1. Cause

When making the front page, you need to call the Post request of WebAPI to send some fields and files (It is equivalent to sending the form asynchronously through ajax and getting the return result), and then getting the return value to determine whether it is successful.

2. Try

#First I tried "jQuery Form Plugin", this thing is a huge pit, implement it and jquery1. The compatibility of 9.2 is not very good. I finally solved the problem of $.browser, but found that I can’t get the return value when using it to upload files.

$("#view").submit(
$("#view").ajaxSubmit({
type: "post",
url: "../api/Article/Add",
dataType: "json",
success: function (msg) {
console.log(msg);
},
error: function (msg) {
$("#resultBox").html("连接服务器失败");
console.log(msg);
}
})
);
Copy after login

For example, the above code, but how to configure it, as long as the file is uploaded, the msg returned in success must be null (under the chromium browser), but there is actually a return value, and it is normal when there is no file. of. What's even more frightening is the Json return value when prompted to download under IE/EDGE.

I looked through the source code of jquery.form.js and found that it is a pseudo-Ajax implemented using Iframe. It is unclear. 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);
Copy after login

These are two different functions that are called when there is a file or not.

3. Solution

After many anti-investigations, we found that xhr (XMLHttpRequest) is a good thing. After testing, both mainstream browsers and mobile browsers support this thing. The following introduces the method of obtaining the native XMLHttpRequest object to upload the form (file) in jquery/zepto's ajax. Reference article: http://www.jb51.net/article/91267.htm

function AjaxForm(formID, options) {
var form = $(formID);
//将form对象直接作为参数 new FormData对象
var formData = new FormData(form[0]);
$("input[type='file']").forEach(function (item, i) {
//获取file对象 即相当于可以直接post的$_FILES数据
var domFile = $(item)[0].files[0];
//追加file 对象
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 not to process the data
options.contentType = false; // tell jQuery not to set contentType
options.xhr = options.xhr ? options.xhr : function () {
//这是关键 获取原生的xhr对象 做以前做的所有事情
var xhr = $.ajaxSettings.xhr();
xhr.upload.onload = function () {
console.log("onload");
}
xhr.upload.onprogress = function (ev) {
if (ev.lengthComputable) {
var percent = 100 * ev.loaded / ev.total;
console.log(percent, ev)
}
}
return xhr;
};
options.success = options.success ? options.success : function (data) {
alert(data)
};
$.ajax(options);
}
//调用
$("#sub").click(function (e) {
AjaxForm("#myForm");
});
Copy after login

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to php Chinese website Other related articles!

Recommended reading:

Ajax+mysq realizes the three-level linkage list of provinces and municipalities

Ajax transmits Json and xml data Detailed explanation of the steps (with code)

The above is the detailed content of Ajax operation form asynchronously uploads files. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Simple steps to upload your own music on Kugou Simple steps to upload your own music on Kugou Mar 25, 2024 pm 10:56 PM

1. Open Kugou Music and click on your profile picture. 2. Click the settings icon in the upper right corner. 3. Click [Upload Music Works]. 4. Click [Upload Works]. 5. Select the song and click [Next]. 6. Finally, click [Upload].

How to upload lyrics to QQ Music How to upload lyrics to QQ Music Feb 23, 2024 pm 11:45 PM

With the advent of the digital age, music platforms have become one of the main ways for people to obtain music. However, sometimes when we listen to songs, we find that there are no lyrics, which is very disturbing. Many people hope that lyrics can be displayed when listening to songs to better understand the content and emotions of the songs. QQ Music, as one of the largest music platforms in China, also provides users with the function of uploading lyrics, so that users can better enjoy music and feel the connotation of the songs. The following will introduce how to upload lyrics on QQ Music. first

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

How to get variables from PHP method using Ajax? How to get variables from PHP method using Ajax? Mar 09, 2024 pm 05:36 PM

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

How to solve the problem of jQuery AJAX error 403? How to solve the problem of jQuery AJAX error 403? Feb 23, 2024 pm 04:27 PM

How to solve the problem of jQueryAJAX error 403? When developing web applications, jQuery is often used to send asynchronous requests. However, sometimes you may encounter error code 403 when using jQueryAJAX, indicating that access is forbidden by the server. This is usually caused by server-side security settings, but there are ways to work around it. This article will introduce how to solve the problem of jQueryAJAX error 403 and provide specific code examples. 1. to make

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

Advanced Guide to Python asyncio: From Beginner to Expert Advanced Guide to Python asyncio: From Beginner to Expert Mar 04, 2024 am 09:43 AM

Concurrent and Asynchronous Programming Concurrent programming deals with multiple tasks executing simultaneously, asynchronous programming is a type of concurrent programming in which tasks do not block threads. asyncio is a library for asynchronous programming in python, which allows programs to perform I/O operations without blocking the main thread. Event loop The core of asyncio is the event loop, which monitors I/O events and schedules corresponding tasks. When a coroutine is ready, the event loop executes it until it waits for I/O operations. It then pauses the coroutine and continues executing other coroutines. Coroutines Coroutines are functions that can pause and resume execution. The asyncdef keyword is used to create coroutines. The coroutine uses the await keyword to wait for the I/O operation to complete. The following basics of asyncio

See all articles