Home Web Front-end JS Tutorial jquery plug-in--ajaxfileupload.js

jquery plug-in--ajaxfileupload.js

Dec 12, 2016 pm 05:36 PM
ajaxfileupload

ajaxfileupload.js

jQuery.extend({
    createUploadIframe: function (id, uri) {//id为当前系统时间字符串,uri是外部传入的json对象的一个参数
        //create frame
        var frameId = 'jUploadFrame' + id; //给iframe添加一个独一无二的id
        var iframeHtml = &#39;<iframe id="&#39; + frameId + &#39;" name="&#39; + frameId + &#39;" style="position:absolute; top:-9999px; left:-9999px"&#39;; //创建iframe元素
        if (window.ActiveXObject) {//判断浏览器是否支持ActiveX控件
            if (typeof uri == &#39;boolean&#39;) {
                iframeHtml += &#39; src="&#39; + &#39;javascript:false&#39; + &#39;"&#39;;
            }            else if (typeof uri == &#39;string&#39;) {
                iframeHtml += &#39; src="&#39; + uri + &#39;"&#39;;
            }
        }
        iframeHtml += &#39; />&#39;;
        jQuery(iframeHtml).appendTo(document.body); //将动态iframe追加到body中
        return jQuery(&#39;#&#39; + frameId).get(0); //返回iframe对象
    },
    createUploadForm: function (id, fileElementId, data) {//id为当前系统时间字符串,fileElementId为页面<input type=&#39;file&#39; />的id,data的值需要根据传入json的键来决定
        //create form    
        var formId = &#39;jUploadForm&#39; + id; //给form添加一个独一无二的id
        var fileId = &#39;jUploadFile&#39; + id; //给<input type=&#39;file&#39; />添加一个独一无二的id
        var form = jQuery(&#39;<form  action="" method="POST" name="&#39; + formId + &#39;" id="&#39; + formId + &#39;" enctype="multipart/form-data" ></form>&#39;); //创建form元素
        if (data) {//通常为false
            for (var i in data) {
                jQuery(&#39;<input type="hidden" name="&#39; + i + &#39;" value="&#39; + data[i] + &#39;" />&#39;).appendTo(form); //根据data的内容,创建隐藏域,这部分我还不知道是什么时候用到。估计是传入json的时候,如果默认传一些参数的话要用到。
            }
        }        var oldElement = jQuery(&#39;#&#39; + fileElementId); //得到页面中的<input type=&#39;file&#39; />对象
        var newElement = jQuery(oldElement).clone(); //克隆页面中的<input type=&#39;file&#39; />对象
        jQuery(oldElement).attr(&#39;id&#39;, fileId); //修改原对象的id
        jQuery(oldElement).before(newElement); //在原对象前插入克隆对象
        jQuery(oldElement).appendTo(form); //把原对象插入到动态form的结尾处
        //set attributes
        jQuery(form).css(&#39;position&#39;, &#39;absolute&#39;); //给动态form添加样式,使其浮动起来,
        jQuery(form).css(&#39;top&#39;, &#39;-1200px&#39;);
        jQuery(form).css(&#39;left&#39;, &#39;-1200px&#39;);
        jQuery(form).appendTo(&#39;body&#39;); //把动态form插入到body中
        return form;
    },
    ajaxFileUpload: function (s) {//这里s是个json对象,传入一些ajax的参数
        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout        
        s = jQuery.extend({}, jQuery.ajaxSettings, s); //此时的s对象是由jQuery.ajaxSettings和原s对象扩展后的对象
        var id = new Date().getTime(); //取当前系统时间,目的是得到一个独一无二的数字
        var form = jQuery.createUploadForm(id, s.fileElementId, (typeof (s.data) == &#39;undefined&#39; ? false : s.data)); //创建动态form
        var io = jQuery.createUploadIframe(id, s.secureuri); //创建动态iframe
        var frameId = &#39;jUploadFrame&#39; + id; //动态iframe的id
        var formId = &#39;jUploadForm&#39; + id; //动态form的id
        // Watch for a new set of requests
        if (s.global && !jQuery.active++) {//当jQuery开始一个ajax请求时发生
            jQuery.event.trigger("ajaxStart"); //触发ajaxStart方法
        }        var requestDone = false; //请求完成标志
        // Create the request object
        var xml = {};        if (s.global)
            jQuery.event.trigger("ajaxSend", [xml, s]); //触发ajaxSend方法
        // Wait for a response to come back
        var uploadCallback = function (isTimeout) {//回调函数
            var io = document.getElementById(frameId); //得到iframe对象
            try {                if (io.contentWindow) {//动态iframe所在窗口对象是否存在
                    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;
                } else if (io.contentDocument) {//动态iframe的文档对象是否存在
                    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);
            }            if (xml || isTimeout == "timeout") {//xml变量被赋值或者isTimeout == "timeout"都表示请求发出,并且有响应
                requestDone = true; //请求完成
                var status;                try {
                    status = isTimeout != "timeout" ? "success" : "error"; //如果不是“超时”,表示请求成功
                    // Make sure that the request was successful or notmodified
                    if (status != "error") {                        // process the data (runs the xml through httpData regardless of callback)
                        var data = jQuery.uploadHttpData(xml, s.dataType); //根据传送的type类型,返回json对象,此时返回的data就是后台操作后的返回结果
                        // If a local callback was specified, fire it and pass it the data
                        if (s.success)
                            s.success(data, status); //执行上传成功的操作
                        // Fire the global callback
                        if (s.global)
                            jQuery.event.trigger("ajaxSuccess", [xml, s]);
                    } else
                        jQuery.handleError(s, xml, status);
                } catch (e) {
                    status = "error";
                    jQuery.handleError(s, xml, status, e);
                }                // The request was completed
                if (s.global)
                    jQuery.event.trigger("ajaxComplete", [xml, s]);                // Handle the global AJAX counter
                if (s.global && ! --jQuery.active)
                    jQuery.event.trigger("ajaxStop");                // Process result
                if (s.complete)
                    s.complete(xml, status);
                jQuery(io).unbind();//移除iframe的事件处理程序
                setTimeout(function () {//设置超时时间
                    try {
                        jQuery(io).remove();//移除动态iframe
                        jQuery(form).remove();//移除动态form
                    } catch (e) {
                        jQuery.handleError(s, xml, null, e);
                    }
                }, 100)
                xml = null
            }
        }        // Timeout checker
        if (s.timeout > 0) {//超时检测
            setTimeout(function () {                // Check to see if the request is still happening
                if (!requestDone) uploadCallback("timeout");//如果请求仍未完成,就发送超时信号
            }, s.timeout);
        }        try {            var form = jQuery(&#39;#&#39; + formId);
            jQuery(form).attr(&#39;action&#39;, s.url);//传入的ajax页面导向url
            jQuery(form).attr(&#39;method&#39;, &#39;POST&#39;);//设置提交表单方式
            jQuery(form).attr(&#39;target&#39;, frameId);//返回的目标iframe,就是创建的动态iframe
            if (form.encoding) {//选择编码方式
                jQuery(form).attr(&#39;encoding&#39;, &#39;multipart/form-data&#39;);
            }            else {
                jQuery(form).attr(&#39;enctype&#39;, &#39;multipart/form-data&#39;);
            }
            jQuery(form).submit();//提交form表单
        } catch (e) {
            jQuery.handleError(s, xml, null, e);
        }
        jQuery(&#39;#&#39; + frameId).load(uploadCallback); //ajax 请求从服务器加载数据,同时传入回调函数
        return { abort: function () { } };
    },
    uploadHttpData: function (r, type) {        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;        // If the type is "script", eval it in global context
        if (type == "script")
            jQuery.globalEval(data);        // Get the JavaScript object, if JSON is used.
        if (type == "json")
            eval("data = " + data);        // evaluate scripts within html
        if (type == "html")
            jQuery("<div>").html(data).evalScripts();        return data;
    }
})
Copy after login

The general method of using the ajaxfileupload.js plug-in

$.ajaxFileUpload
(
    {
        url: &#39;../../XXXX/XXXX.aspx&#39;, //用于文件上传的服务器端请求地址
        secureuri: false,           //一般设置为false
        fileElementId: $("input#xxx").attr("id"), //文件上传控件的id属性  <input type="file" id="file" name="file" /> 注意,这里一定要有name值   
                                                //$("form").serialize(),表单序列化。指把所有元素的ID,NAME 等全部发过去
        dataType: &#39;json&#39;,//返回值类型 一般设置为json
        complete: function () {//只要完成即执行,最后执行
        },
        success: function (data, status)  //服务器成功响应处理函数
        {            if (typeof (data.error) != &#39;undefined&#39;) {                if (data.error != &#39;&#39;) {                    if (data.error == "1001") {//这个error(错误码)是由自己定义的,根据后台返回的json对象的键值而判断
                    }                    else if (data.error == "1002") {
                    }
                    alert(data.msg);//同error
                    return;
                } else {
                    alert(data.msg);
                }
            }            /*                *    这里就是做一些其他操作,比如把图片显示到某控件中去之类的。                */
        },
        error: function (data, status, e)//服务器响应失败处理函数
        {
            alert(e);
        }
    }
)
Copy after login


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

Video Face Swap

Video Face Swap

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

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)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

See all articles