Home Web Front-end JS Tutorial ajax file uploaded successfully, solving browser compatibility issues

ajax file uploaded successfully, solving browser compatibility issues

May 23, 2018 pm 05:37 PM
ajax firefox webkit

这篇文章主要为大家详细介绍了ajax文件上传的相关资料,成功解决了浏览器兼容问题,感兴趣的小伙伴们可以参考一下

ajaxfileupload控制很好用,不过发现上传文件后的结果为被浏览器处理,IE不会,谷哥和火狐都会进行处理,而且谷哥和火狐处理后的结果都不一样,这里对以上三种浏览器进行了兼容性调整。

jQuery.extend({
 createUploadIframe: function(id, uri)
 {
 //create frame
 var frameId = 'jUploadFrame' + id;
 var iframeHtml = &#39;<iframe id="&#39; + frameId + &#39;" name="&#39; + frameId + &#39;" style="position:absolute; top:-9999px; left:-9999px"&#39;;
 if(window.ActiveXObject)
 {
  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);
 
 return jQuery(&#39;#&#39; + frameId).get(0);  
 },
 createUploadForm: function(id,fileElementId,data,fileElement)
 {
 //create form 
 var formId = &#39;jUploadForm&#39; + id;
 var fileId = &#39;jUploadFile&#39; + id;
 var form = jQuery(&#39;<form action="" method="POST" name="&#39; + formId + &#39;" id="&#39; + formId + &#39;" enctype="multipart/form-data"></form>&#39;); 
 if(data)
 {
  for(var i in data)
  {
  jQuery(&#39;<input type="hidden" name="&#39; + i + &#39;" value="&#39; + data[i] + &#39;" />&#39;).appendTo(form);
  }  
 }
 var oldElement;
 if(fileElement == null)
  oldElement = jQuery(&#39;#&#39; + fileElementId);
 else
  oldElement = fileElement;
  
 var newElement = jQuery(oldElement).clone();
 jQuery(oldElement).attr(&#39;id&#39;, fileId);
 jQuery(oldElement).before(newElement);
 jQuery(oldElement).appendTo(form);
  
 //set attributes
 jQuery(form).css(&#39;position&#39;, &#39;absolute&#39;);
 jQuery(form).css(&#39;top&#39;, &#39;-1200px&#39;);
 jQuery(form).css(&#39;left&#39;, &#39;-1200px&#39;);
 jQuery(form).appendTo(&#39;body&#39;); 
 return form;
 },
 
 ajaxFileUpload: function(s) {
 // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout 
 s = jQuery.extend({}, jQuery.ajaxSettings, s);
 var id = new Date().getTime() 
 var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)==&#39;undefined&#39;?false:s.data),s.fileElement);
 var io = jQuery.createUploadIframe(id, s.secureuri);
 var frameId = &#39;jUploadFrame&#39; + id;
 var formId = &#39;jUploadForm&#39; + id; 
 // Watch for a new set of requests
 if ( s.global && ! jQuery.active++ )
 {
  jQuery.event.trigger( "ajaxStart" );
 }  
 var requestDone = false;
 // Create the request object
 var xml = {} 
 if ( s.global )
  jQuery.event.trigger("ajaxSend", [xml, s]);
 // Wait for a response to come back
 var uploadCallback = function(isTimeout)
 {  
  var io = document.getElementById(frameId);
  try
  {  
  if(io.contentWindow)
  {
   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)
  {
   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") 
  {  
  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)
   console.log( jQuery.uploadHttpData);
   var data = jQuery.uploadHttpData(xml,s.dataType ); 
   // 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()
 
  setTimeout(function()
     { try
     {
      jQuery(io).remove();
      jQuery(form).remove(); 
      
     } 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);
  jQuery(form).attr(&#39;method&#39;, &#39;POST&#39;);
  jQuery(form).attr(&#39;target&#39;, frameId);
  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();
 
 } catch(e) 
 {  
  jQuery.handleError(s, xml, null, e);
 }
  
 jQuery(&#39;#&#39; + frameId).load(uploadCallback);
 return {abort: function(){
  try
  {
  jQuery(&#39;#&#39; + frameId).remove();
  jQuery(form).remove();
  }
  catch(e){}
 }};
 },
 
 uploadHttpData: function( r, type ) {
 var data ="";
 data = (type == "xml" ? r.responseXML : r.responseText);
 if ( type == "script" )
  jQuery.globalEval( data );
 /**
  * auth garen 2016-06-17
  * 对文件上传后的响应结果进行处理,支持IE FF GC
  * */
 if ( type == "json" ){
  var reg ="";
  if(data.indexOf("<pre class="brush:php;toolbar:false">")>-1){
  reg=/<pre class="brush:php;toolbar:false">(.+)<\/pre>/g;
  }else{  
  reg=/<pre.+?>(.+)<\/pre>/g; 
  }
  var result = data.match(reg);
  var stri1=RegExp.$1; 
  if(stri1!=null&&stri1!="" &&stri1.trim().length>0){
   data = stri1;  
  }
  eval( "data =" + data);
 }
 if ( type == "html" )
  jQuery("<p>").html(data).evalScripts();
 return data;
 },
 
 handleError: function( s, xml, status, e ) {
 // If a local callback was specified, fire it
 if ( s.error )
  s.error( xml, status, e );
 
 // Fire the global callback
 if ( s.global )
  jQuery.event.trigger( "ajaxError", [xml, s, e] );
 }
});
Copy after login

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

Ajax实现智能提示搜索功能

反向Ajax 30分钟快速掌握

Ajax全局加载框(Loading效果)的配置

The above is the detailed content of ajax file uploaded successfully, solving browser compatibility issues. 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)

How to remove Firefox Snap in Ubuntu Linux? How to remove Firefox Snap in Ubuntu Linux? Feb 21, 2024 pm 07:00 PM

To remove FirefoxSnap in Ubuntu Linux, you can follow these steps: Open a terminal and log in to your Ubuntu system as administrator. Run the following command to uninstall FirefoxSnap: sudosnapremovefirefox You will be prompted for your administrator password. Enter your password and press Enter to confirm. Wait for command execution to complete. Once completed, FirefoxSnap will be completely removed. Note that this will remove versions of Firefox installed via the Snap package manager. If you installed another version of Firefox through other means (such as the APT package manager), you will not be affected. Go through the above steps

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.

PHP vs. Ajax: Solutions for creating dynamically loaded content PHP vs. Ajax: Solutions for creating dynamically loaded content Jun 06, 2024 pm 01:12 PM

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

Firefox 113 new features: support for AV1 animations, enhanced password generator and picture-in-picture features Firefox 113 new features: support for AV1 animations, enhanced password generator and picture-in-picture features Mar 05, 2024 pm 05:20 PM

According to recent news, while Mozilla released the stable version of Firefox 112, it also announced that the next major version, Firefox 113, has entered the Beta channel and supports AV1 animations, enhanced password generator and picture-in-picture features. The main new functions/features of Firefox 113 are as follows: Support for AV1 format animated images (AVIS); Enhance the security of the password generator by introducing special characters; Enhance the picture-in-picture function, support rewind, display video time, and enable full screen more easily Mode provides official DEB installation files for Debian and Ubuntu distributions. Updated bookmark import feature, icons for imported bookmarks are supported by default. Hardware accelerated AV1 video decoding is enabled by default on supported hardware using w

See all articles