首頁 web前端 js教程 ajaxfileupload.js的使用實例詳解

ajaxfileupload.js的使用實例詳解

Jun 30, 2017 pm 03:12 PM
javascript jquery

在網頁應用程式中,通常會用到上傳檔案或圖片什麼的到伺服器,那麼可以用ajaxfileupload.js,但是在使用ajaxfileupload.js時候,當伺服器回傳的json帶有&#符號的時候,回傳的data資料裡面所有的&被轉義成了&
下面的ajaxfileupload.js是經過修改的檔案上傳函式庫。

jQuery.extend({/** createUploadIframe 创建上传的iframe
     * @param id 传递当前系统的时间字符串
     * @param uri 传入的json对象的一个参数
     * */createUploadIframe: function (id, uri) {//iframe添加一个idvar frameId = 'jUploadFrame' + id;//创建iframe元素var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';if (window.ActiveXObject) {//判断浏览器是否支持ActiveX控件if (typeof uri == 'boolean') {//阻止提交数据iframeHtml += ' src="' + 'javascript:false' + '"';
            }else if (typeof uri == 'string') {
                iframeHtml += ' src="' + uri + '"';
            }
        }
        iframeHtml += ' />';//将动态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('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data" ></form>');if (data) {for (var i in data) {//根据data提交的数据,创建隐藏域jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
            }
        }//得到页面中的<input type='file' />对象if (typeof(fileElementId) == 'string') {  
            fileElementId = fileElementId.split(',');
        }for (var i=0,j = fileElementId.length;i < j; i++) {          var oldElement = jQuery('#' + fileElementId[i]);          //克隆页面中的<input type='file' />对象  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("<div>").html(data).evalScripts();
        }return data;
    },
    handleError: function( s, xhr, status, e ){// If a local callback was specified, fire itif ( s.error ) {
            s.error.call( s.context || s, xhr, status, e );
        }// Fire the global callbackif ( s.global ) {
            (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
        }
    }
})
登入後複製

下面是呼叫方式:

$.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);
    }
 })
登入後複製

註:如果有&符號回,這dataType改成text,然後把傳回的data字串透過JSON.parse()處理。

以上是ajaxfileupload.js的使用實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

<🎜>:泡泡膠模擬器無窮大 - 如何獲取和使用皇家鑰匙
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
北端:融合系統,解釋
3 週前 By 尊渡假赌尊渡假赌尊渡假赌
Mandragora:巫婆樹的耳語 - 如何解鎖抓鉤
3 週前 By 尊渡假赌尊渡假赌尊渡假赌

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

熱門話題

Java教學
1665
14
CakePHP 教程
1424
52
Laravel 教程
1322
25
PHP教程
1270
29
C# 教程
1250
24
jQuery引用方法詳解:快速上手指南 jQuery引用方法詳解:快速上手指南 Feb 27, 2024 pm 06:45 PM

jQuery引用方法詳解:快速上手指南jQuery是一個受歡迎的JavaScript庫,被廣泛用於網站開發中,它簡化了JavaScript編程,並為開發者提供了豐富的功能和特性。本文將詳細介紹jQuery的引用方法,並提供具體的程式碼範例,幫助讀者快速上手。引入jQuery首先,我們需要在HTML檔案中引入jQuery函式庫。可以透過CDN連結的方式引入,也可以下載

jQuery中如何使用PUT請求方式? jQuery中如何使用PUT請求方式? Feb 28, 2024 pm 03:12 PM

jQuery中如何使用PUT請求方式?在jQuery中,發送PUT請求的方法與發送其他類型的請求類似,但需要注意一些細節和參數設定。 PUT請求通常用於更新資源,例如更新資料庫中的資料或更新伺服器上的檔案。以下是在jQuery中使用PUT請求方式的具體程式碼範例。首先,確保引入了jQuery庫文件,然後可以透過以下方式發送PUT請求:$.ajax({u

jQuery小技巧:快速修改頁面所有a標籤的文本 jQuery小技巧:快速修改頁面所有a標籤的文本 Feb 28, 2024 pm 09:06 PM

標題:jQuery小技巧:快速修改頁面所有a標籤的文字在網頁開發中,我們經常需要對頁面中的元素進行修改和操作。使用jQuery時,有時候需要一次修改頁面中所有a標籤的文字內容,這樣可以節省時間和精力。以下將介紹如何使用jQuery快速修改頁面所有a標籤的文本,同時給出具體的程式碼範例。首先,我們需要引入jQuery庫文件,確保在頁面中引入了以下程式碼:&lt

使用jQuery修改所有a標籤的文字內容 使用jQuery修改所有a標籤的文字內容 Feb 28, 2024 pm 05:42 PM

標題:使用jQuery修改所有a標籤的文字內容jQuery是一款受歡迎的JavaScript庫,被廣泛用於處理DOM操作。在網頁開發中,經常會遇到需要修改頁面上連結標籤(a標籤)的文字內容的需求。本文將介紹如何使用jQuery來實現這個目標,並提供具體的程式碼範例。首先,我們需要在頁面中引入jQuery庫。在HTML檔案中加入以下程式碼:

jQuery如何移除元素的height屬性? jQuery如何移除元素的height屬性? Feb 28, 2024 am 08:39 AM

jQuery如何移除元素的height屬性?在前端開發中,經常會遇到需要操作元素的高度屬性的需求。有時候,我們可能需要動態改變元素的高度,而有時候又需要移除元素的高度屬性。本文將介紹如何使用jQuery來移除元素的高度屬性,並提供具體的程式碼範例。在使用jQuery操作高度屬性之前,我們首先需要了解CSS中的height屬性。 height屬性用於設定元素的高度

了解jQuery中eq的作用及應用場景 了解jQuery中eq的作用及應用場景 Feb 28, 2024 pm 01:15 PM

jQuery是一種流行的JavaScript庫,被廣泛用於處理網頁中的DOM操作和事件處理。在jQuery中,eq()方法是用來選擇指定索引位置的元素的方法,具體使用方法和應用場景如下。在jQuery中,eq()方法選擇指定索引位置的元素。索引位置從0開始計數,即第一個元素的索引是0,第二個元素的索引是1,依此類推。 eq()方法的語法如下:$("s

使用jQuery為表格新增一行的方法介紹 使用jQuery為表格新增一行的方法介紹 Feb 29, 2024 am 08:12 AM

jQuery是一個受歡迎的JavaScript函式庫,廣泛用於網頁開發。在網頁開發過程中,經常需要透過JavaScript動態地在表格中新增一行。本文將介紹如何使用jQuery為表格新增一行,並提供具體的程式碼範例。首先,我們需要在HTML頁面中引入jQuery函式庫。可以透過以下程式碼在標籤中引入jQuery庫:

如何判斷jQuery元素是否具有特定屬性? 如何判斷jQuery元素是否具有特定屬性? Feb 29, 2024 am 09:03 AM

如何判斷jQuery元素是否具有特定屬性?在使用jQuery操作DOM元素時,常會遇到需要判斷元素是否具有某個特定屬性的情況。在這種情況下,我們可以藉助jQuery提供的方法來輕鬆實現這項功能。以下將介紹兩種常用的方法來判斷一個jQuery元素是否具有特定屬性,並附上具體的程式碼範例。方法一:使用attr()方法和typeof運算子//判斷元素是否具有特定屬

See all articles