In web applications, it is generally used to upload files or pictures to the server, then you can use ajaxfileupload.js, but when using ajaxfileupload.js, when the json returned by the server contains &
symbol, all &
in the returned data are escaped into &
.
The ajaxfileupload.js below is a modified file upload library.
jQuery.extend({/** createUploadIframe 创建上传的iframe * @param id 传递当前系统的时间字符串 * @param uri 传入的json对象的一个参数 * */createUploadIframe: function (id, uri) {//iframe添加一个idvar frameId = 'jUploadFrame' + id;//创建iframe元素var iframeHtml = '<iframe></iframe>';//将动态iframe追加到body中 jQuery(iframeHtml).appendTo(document.body);//返回iframe对象return jQuery('#' + frameId).get(0); },/** createUploadForm 创建form * @param id 当前系统时间字符串 * @param fileElementId 为页面input type='file'的id * @param data 向服务器传递的值 如 data:{key1:value1,key2:value2} * */createUploadForm: function (id, fileElementId, data) {//给form添加idvar formId = 'jUploadForm' + id;//给type为file的上传按钮添加idvar fileId = 'jUploadFile' + id;//创建form元素var form = jQuery('');if (data) {for (var i in data) {//根据data提交的数据,创建隐藏域jQuery('').appendTo(form); } }//得到页面中的对象if (typeof(fileElementId) == 'string') { fileElementId = fileElementId.split(','); }for (var i=0,j = fileElementId.length;i 对象 var newElement = jQuery(oldElement).clone(true); //修改原对象的id jQuery(oldElement).attr('id', fileId); //在原对象前插入克隆对象 jQuery(oldElement).before(newElement); //把原对象插入到动态form的结尾处 jQuery(oldElement).appendTo(form); } //给动态form添加样式jQuery(form).css('position', 'absolute'); jQuery(form).css('top', '-1200px'); jQuery(form).css('left', '-1200px'); jQuery(form).appendTo('body');return form; },/** ajaxFileUpload ajax上传请求 * @param s 传入一些ajax的参数 * */ajaxFileUpload: function (s) { s = jQuery.extend({}, jQuery.ajaxSettings, s);var id = new Date().getTime();//创建动态formvar form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == 'undefined' ? false : s.data));//创建动态iframe s.secureuri 是否需要安全协议,一般置为falsevar io = jQuery.createUploadIframe(id, s.secureuri);//动态iframe的idvar frameId = 'jUploadFrame' + id;//动态form的idvar formId = 'jUploadForm' + id;//当jQuery开始一个ajax请求时发生,global表示是否触发全局ajax事件,默认是true;if (s.global && !jQuery.active++) {//触发ajaxStart方法jQuery.event.trigger("ajaxStart"); }//请求完成标志var requestDone = false;// 创建请求对象var xml = {};if (s.global){//触发ajaxSend方法jQuery.event.trigger("ajaxSend", [xml, s]); }//回调函数var uploadCallback = function (isTimeout) {//得到iframe对象var io = document.getElementById(frameId);try {//动态iframe所在窗口对象是否存在if (io.contentWindow) {if(s.dataType=='text'){ xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.textContent : null; }else{ xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML : null; } xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument : io.contentWindow.document; }//动态iframe的文档对象是否存在else if (io.contentDocument) {if(s.dataType=='text'){ xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.textContent : null; }else{ xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null; } xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML : null; xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument : io.contentDocument.document; } } catch (e) { jQuery.handleError(s, xml, null, e); }//xml变量被赋值或者isTimeout == "timeout"都表示请求发出,并且有响应if (xml || isTimeout == "timeout") {//请求完成requestDone = true;var status;try {//如果不是“超时”,表示请求成功status = isTimeout != "timeout" ? "success" : "error";// Make sure that the request was successful or notmodifiedif (status != "error") {// process the data (runs the xml through httpData regardless of callback)var data = jQuery.uploadHttpData(xml, s.dataType);// If a local callback was specified, fire it and pass it the dataif (s.success){//执行上传成功的操作 s.success(data, status); }// Fire the global callbackif (s.global){ jQuery.event.trigger("ajaxSuccess", [xml, s]); } } else{ jQuery.handleError(s, xml, status); } }catch (e) { status = "error"; jQuery.handleError(s, xml, status, e); }if (s.global){// The request was completedjQuery.event.trigger("ajaxComplete", [xml, s]); }if (s.global && ! --jQuery.active){ jQuery.event.trigger("ajaxStop"); }if (s.complete){ s.complete(xml, status); }//移除iframe的事件处理程序 jQuery(io).unbind(); setTimeout(function () {//设置超时时间try {//移除动态iframe与动态form jQuery(io).remove(); jQuery(form).remove(); }catch (e) { jQuery.handleError(s, xml, null, e); } }, 100) xml = null} }//超时检测if (s.timeout > 0) { setTimeout(function () {//如果请求仍未完成,就发送超时信号if (!requestDone) uploadCallback("timeout"); }, s.timeout); }try {var form = jQuery('#' + formId); jQuery(form).attr('action', s.url);//传入的ajax页面导向urljQuery(form).attr('method', 'POST');//设置提交表单方式jQuery(form).attr('target', frameId);//返回的目标iframe,就是创建的动态iframeif (form.encoding) {//选择编码方式jQuery(form).attr('encoding', 'multipart/form-data'); }else { jQuery(form).attr('enctype', 'multipart/form-data'); } jQuery(form).submit();//提交form表单}catch (e) { jQuery.handleError(s, xml, null, e); } jQuery('#' + frameId).load(uploadCallback); //ajax 请求从服务器加载数据,同时传入回调函数return { abort: function () { } }; }, uploadHttpData: function (r, type) {var data = !type;// If the type is "script", eval it in global contextdata = type == "xml" || data ? r.responseXML : r.responseText;if (type == "script"){ jQuery.globalEval(data); }// Get the JavaScript object, if JSON is used.if (type == "json"){ eval("data = " + data); }if (type == "html"){ jQuery("
The following is the calling method:
$.ajaxFileUpload({ url: 'ps.php',//一般设置为falsesecureuri: false, data:{ email:email },//文件上传控件的id属性fileElementId: $("input#xxx").attr("id"), //返回值类型 一般设置为json,但是如果返回的数据有&等特殊符号,这儿改成textdataType: 'text', success: function (data, status) {//如果dataType为text,那么这儿需要把返回的字符串转成对象data = JSON.parse(data); }, error: function (data, status, e){ console.log(e); } })
Note: If there is an & symbol returned, change the dataType to text, and then return the data Strings are processed via JSON.parse().
The above is the detailed content of Detailed explanation of usage examples of ajaxfileupload.js. For more information, please follow other related articles on the PHP Chinese website!

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
