Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to realize Ajax upload files and set headers by jQuery

Shulou Source: shulou.com Published: 2022-05-31 13:47:42 10月27日 Update

This article mainly introduces "jQuery how to achieve Ajax upload files while setting headers". In daily operation, I believe many people have doubts about how to achieve Ajax upload files while setting headers in jQuery. Xiaobian consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful for you to answer the doubts of "how to achieve Ajax upload files while setting headers". Next, please follow the editor to study!

Example code:

Function ajaxSubmitForm () {var option = {url: cache.batchImport, type: 'POST', dataType:' json', headers: {"token": localStorage.getItem ('token')}, / / add request header success: function (data) {console.log (' success')}, error: function (data) {console.log ('error');}} $("# userForm") .ajaxSubmit (option); return false; / / better return false, because if the button type is submit, the form will be submitted again; return false to prevent the form from being submitted again

Encountered a problem, to upload files at the same time to set headers information, but form form submission can upload files can not be set headers,ajax can not be set headers can not upload files, and then found on the Internet jQuery.form can be achieved, the code as above.

Because the file button can not be styled, you have to use a button to indirectly trigger file, but this cannot be achieved on ie, because ie can only directly trigger the button to achieve the function, so set the location and size of file to be the same as button, but the transparency setting to 0 overrides button to achieve the requirement of direct trigger control compatible with ie. After compatibility, the style has a problem with other browsers.

Compatible with other browser style codes are as follows:

Var isIE = navigator.userAgent.indexOf ('MSIE') >-1; if (! isIE) {$(' # filePath'). Css);} at this point, the study on "how to upload files on Ajax while setting headers on jQuery" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Tags: Files meanwhile buttons learning code styles forms questions more browsers browsing utility next location information again function size header Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno vpn Microsoft MariaDB Shulou Tech Info NVidia