Html代码
<table id="deploy_application" class="bordered-table"> <tr> <td id="application_file"> <input id="file_field" type="file" name="application" size="20" /> </td> <td id="application_submit"> <input id="submit_button" type="submit" value="Upload" onclick="uploadFile()" /> </td> </tr> </table>
最近在使用ajaxFileUpload插件做文件上传时,后端返回json格式的数据,js代码如下:
function ajaxFileUpload() {
$.ajaxFileUpload
(
{
url: '/upload',
secureuri: false,
fileElementId: 'file_field',
dataType: 'json', //这里选择了json
success: function (data, status) {
alert(data);
},
error: function (data, status, e) {
alert(e);
}
}
)
}
结果在chrome和FireFox浏览器出现如下错误:
网上查了下原因,是因为Server端的Response上加上了contentType="application/json"。但有时后端这么做是必须的,所以修改ajaxFileUpload源码,将<pre></pre>标签去掉,如下:
Js代码
1 uploadHttpData: function( r, type ) { 2 var data = !type; 3 data = type == "xml" || data ? r.responseXML : r.responseText; 4 // If the type is "script", eval it in global context 5 if ( type == "script" ) 6 jQuery.globalEval( data ); 7 // Get the JavaScript object, if JSON is used. 8 if ( type == "json" ) { 9 以下为新增代码/// 10 data = r.responseText; 11 var start = data.indexOf(">"); 12 if(start != -1) { 13 var end = data.indexOf("<", start + 1); 14 if(end != -1) { 15 data = data.substring(start + 1, end); 16 } 17 } 18 ///以上为新增代码/// 19 eval( "data = " + data); 20 } 21 // evaluate scripts within html 22 if ( type == "html" ) 23 jQuery("<div>").html(data).evalScripts(); 24 25 return data; 26 }
至此,大工告成,ajaxFileUpload的dataType正常使用json。