现象:脚本调用成功,文件上传也成功,但是始终进入error的回调函数。

1. ajaxfileupload.js

jQuery.extend({

    handleError: function( s, xhr, status, e ){
      // If a local callback was specified, fire it
      if ( s.error ) {
        s.error.call( s.context || s, xhr, status, e );
      }   

      // Fire the global callback
      if ( s.global ) {
        (s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
      }
    },

    createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id; if(window.ActiveXObject) {
var io = document.createElement('<iframe id="' + frameId + '" name="' + frameId + '" />');
if(typeof uri== 'boolean'){
io.src = 'javascript:false';
}
else if(typeof uri== 'string'){
io.src = uri;
}
}
else {
var io = document.createElement('iframe');
io.id = frameId;
io.name = frameId;
}
io.style.position = 'absolute';
io.style.top = '-1000px';
io.style.left = '-1000px'; document.body.appendChild(io); return io
},
createUploadForm: function(id, fileElementId)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = $('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
var oldElement = $('#' + fileElementId);
var newElement = $(oldElement).clone();
$(oldElement).attr('id', fileId);
$(oldElement).before(newElement);
$(oldElement).appendTo(form);
//set attributes
$(form).css('position', 'absolute');
$(form).css('top', '-1200px');
$(form).css('left', '-1200px');
$(form).appendTo('body');
return form;
},
addOtherRequestsToForm: function(form,data)
{
// add extra parameter
var originalElement = $('<input type="hidden" name="" value="">');
for (var key in data) {
name = key;
value = data[key];
var cloneElement = originalElement.clone();
cloneElement.attr({'name':name,'value':value});
$(cloneElement).appendTo(form);
}
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);
if ( s.data ) form = jQuery.addOtherRequestsToForm(form,s.data);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + 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)
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
{
$(io).remove();
$(form).remove(); } catch(e)
{
jQuery.handleError(s, xml, null, e);
} }, ) xml = null }
}
// Timeout checker
if ( s.timeout > )
{
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( "timeout" );
}, s.timeout);
}
try
{
// var io = $('#' + frameId);
var form = $('#' + formId);
$(form).attr('action', s.url);
$(form).attr('method', 'POST');
$(form).attr('target', frameId);
if(form.encoding)
{
form.encoding = 'multipart/form-data';
}
else
{
form.enctype = 'multipart/form-data';
}
$(form).submit(); } catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if(window.attachEvent){
document.getElementById(frameId).attachEvent('onload', uploadCallback);
}
else{
document.getElementById(frameId).addEventListener('load', uploadCallback, false);
}
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" )
{
// If you add mimetype in your response,
// you have to delete the '<pre></pre>' tag.
// The pre tag in Chrome has attribute, so have to use regex to remove
var data = r.responseText;
var rx = new RegExp("<pre.*?>(.*?)</pre>","i");
var am = rx.exec(data);
//this is the desired data extracted
var data = (am) ? am[] : ""; //the only submatch or empty
eval( "data = " + data );
}
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts();
//alert($('param', data).each(function(){alert($(this).attr('value'));}));
return data;
}
})

2. 网页的示例代码

<form enctype="multipart/form-data" id="fileForm">
<div class="form-group">
<label class="col-sm-3 control-label">FILE</label>
<div class="col-sm-9" id="fileDiv">
<input type="file" name="ivrFile" id="ivrFile"/>
</div>
</div>
<div>
<input type="button" value="上传" id="fileSubBtn">
</div>
<p><img id="img1" alt="上传成功啦" src="" /></p>
</form>

3.脚本的示例代码

<script type="text/javascript">
$(function () {
$("#fileSubBtn").click(function() {
ajaxFileUpload();
})
})
function ajaxFileUpload() {
$.ajaxFileUpload
(
{
url: 'uploadIvrWav1', //用于文件上传的服务器端请求地址
secureuri: false, //是否需要安全协议,一般设置为false
fileElementId: 'ivrFile', //文件上传域的ID
dataType: 'json', //返回值类型 一般设置为json
success: function (data, status) //服务器成功响应处理函数
{
$("#img1").attr("src", data.imgurl);
if (typeof (data.error) != 'undefined') {
if (data.error != '') {
alert(data.error);
} else {
alert(data.msg);
}
}
},
error: function (data, status, e)//服务器响应失败处理函数
{
alert(e);
}
}
)
return false;
}
</script>

二、问题定位及解决

我的服务器返回的是json数据,修改返回json数据的逻辑处理如下:

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();
//alert($('param', data).each(function(){alert($(this).attr('value'));}));
return data;
}

ajaxupload.js调用始终进入error回调的更多相关文章

  1. Js调用Android回调处理

    通常在混合app中经常会使用js调用native的方法,一般是: window.nativeApp.call(XXX); 直接调用native方法,对于简单的处理倒是可以,如果需要回调呢?期待的方式是 ...

  2. 桥接:JS调用安卓方法报错Uncaught Error: Error calling method on NPObject

    说一说自己粗心踩到的一个不算坑的坑: 项目是安卓webview嵌入SPA单页应用页面,涉及到JS调用原生安卓方法,但就是在调用安卓方法时死活一直报错xxx  NPObject一堆错误.写了一个测试页面 ...

  3. JS调用JCEF方法

    坐下写这篇文章的时候,内心还是有一点点小激动的,折腾了一个多星期,踩了一个又一个的坑,终于找到一条可以走通的路,内心的喜悦相信经历过的人都会明白~~~~~今儿个老百姓啊,真呀个真高兴啊,哈哈,好了,废 ...

  4. windows下node.js调用bat

    node.js调用bat需要用到Child Processes模块 因为bat是文件,所以需要使用execFile方法   如果指定了cwd,它会切换bat执行的目录,类似cd的功能,如果未指定默认为 ...

  5. iOS JS 交互之利用系统JSContext实现 JS调用OC方法以及Objective-C调用JavaScript方法

    ios js 交互分为两块: 1.oc调用js 这一块实现起来比较简单, 我的项目中加载的是本地的html,js,css,需要注意的是当你向工程中拖入这些文件时,选择拷贝到工程中,(拖入的文件夹是蓝色 ...

  6. 从微信小程序到鸿蒙js开发【15】——JS调用Java

    鸿蒙入门指南,小白速来!0基础学习路线分享,高效学习方法,重点答疑解惑--->[课程入口] 目录:1.新建一个Service Ability2.完善代码逻辑3.JS端远程调用4.<从微信小 ...

  7. c#JS调用

    using MSScriptControl; using System; using System.Collections.Generic; using System.Reflection; usin ...

  8. JS调用OC方法并传值,OC调用JS方法并传值////////////////////////zz

     iOS开发-基于原生JS与OC方法互相调用并传值(附HTML代码)     最近项目里面有有个商品活动界面,要与web端传值,将用户在网页点击的商品id 传给客户端,也就是js交互,其实再说明白一点 ...

  9. js调用soapWebService服务

    js调用soapWebService服务 什么是 SOAP? SOAP 指简易对象访问协议 SOAP 是一种通信协议 SOAP 用于应用程序之间的通信 SOAP 是一种用于发送消息的格式 SOAP 被 ...

随机推荐

  1. vmware目录2

    http://www.globalknowledge.com/training/course.asp?pageid=9&courseid=17880&country=United+St ...

  2. 机器学习-分类器-Adaboost原理

    Adaboost原理 Adaboost(AdaptiveBoosting)是一种迭代算法,通过对训练集不断训练弱分类器,然后把这些弱分类器集合起来,构成强分类器.adaboost算法训练的过程中,初始 ...

  3. Linux内核配置.config文件

    在命令行中,进入顶层内核目录,并输入命令make menuconfig,就可以启动一个基于菜单的内核配置编辑器.从这里开始,你可以访问每个可用的配置参数,并生成一个定制的内核配置. 当你退出配置编辑器 ...

  4. JAVA GC优化入门

    为什么需要优化GC? JAVA的GC是面试必考的题目,可是在实际项目中什么时候使用GC哪?或者应该什么时候优化GC哪?有句名言:“GC优化永远是最后一项任务”. 在使用GC之前,应该考虑一下进行GC的 ...

  5. SQLServer中char、varchar、nchar、nvarchar的区别

    http://www.cnblogs.com/14lcj/archive/2012/07/08/2581234.html SQLServer中char.varchar.nchar.nvarchar的区 ...

  6. LIST OF NOSQL DATABASES [currently 150]

    http://nosql-database.org Core NoSQL Systems: [Mostly originated out of a Web 2.0 need] Wide Column ...

  7. kube-proxy源代码分析

    摘要:假设你对kube-proxy的工作原理有一定的了解.本文基于kubernetes v1.5代码对kube-proxy的源代码文件夹结构进行了分析,并以iptables mode为例进行了完整流程 ...

  8. JSTL学习笔记

    转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/6684442.html  一:JSTL用途 JSP标准标签库(JSTL)是一个JSP标签集合,它封装了JSP应用 ...

  9. 【Thinking in Java】读书笔记

    转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/6480258.html 第三章:操作符 1:基本数据类型的比较用 ==.!=,引用类型的==.!=是针对地址的比 ...

  10. Java千百问_05面向对象(005)_接口和抽象类有什么差别

    点击进入_很多其它_Java千百问 1.接口和抽象类有什么差别 在Java语言中.抽象类abstract class和接口interface是抽象定义的两种机制. 正是因为这两种机制的存在,才赋予了J ...