阅读更多
最近在项目中遇到一个非常棘手的问题,就是在为页面设置了document.domain时,ajaxfileupload出现跨域错误,究其原因是页面的domain被设置为***.com时,而ajaxfileupload post to 的页面的域并非根域***.com,而是一个二级的类似abc.***.com的域名,因此会引发无权限的错误。
花了2天的时间终于解决这个问题。
修改后的ajaxfileupload关键代码如下:
var uploadCallback = function(isTimeout) {
var io = document.getElementById(frameId);
var execontent = function(){
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) {
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 handleError(s, xml, status);
} catch(e) {
status = "error";
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) {
handleError(s, xml, null, e);
}
},
100);
xml = null;
}
};
var crossdomain = !jQuery.browser.msie || document.domain == location.hostname;
if(!crossdomain) {
io.src="javascript:try{"
+"document.domain=window.location.hostname.split('.').reverse().slice(0,2).reverse().join('.');"
+"parent.document.getElementById('"+ frameId +"').setAttribute('uploaded','uploaded');"
+"}catch(e){}";
var timer = window.setInterval(function(){
try{
if(io.getAttribute("uploaded") == "uploaded") {
crossdomain = true;
window.clearInterval(timer);
execontent();
}
}catch(e){}
},1000);
} else {
execontent();
}
};
解决问题的思路是,如果是IE浏览器并且为当前页面设置了document.domain,那么在创建的iframe提交后,使用iframe的src属性执行一段js代码,从而改变该iframe页面的domain属性,达到同域的目的。
http://www.qingniao.it/index.php?title=Jquery%E6%8F%92%E4%BB%B6ajaxfileupload%E7%9A%84%E4%B8%80%E6%AC%A1%E8%B7%A8%E5%9F%9F%E4%BD%93%E9%AA%8C