天空小小岛技术网站

标题: jquery.form.js 上传文件时 file文件域与document.domain有冲突(引起跨域问题) [打印本页]

作者: s.Bo    时间: 2013-11-14 16:46
标题: jquery.form.js 上传文件时 file文件域与document.domain有冲突(引起跨域问题)
最近在使用jquery.form.js的ajaxForm、ajaxSubmit方法,如果表单中有file文件域
如果 此时文件域被  document.domain="XXX.com"; 修改 ,则IE下无法和Iframe通信,返回结果都无法执行到success。

经查过后发现,在IE同一域下,在父页面或在iframe页面中,只要设置了document.domain,无论是和当前域名相同还是根域名,均视为跨域,所以才会出现拒绝访问的错误,即使你这样写document.domain=document.domain;都会导致无法正常和Iframe(也是同域下)进行通信,IE下抛出的错误是:SCRIPT5: 拒绝访问,导致无法操作iframe中的内容。

网上有人参考twitter的SDK的代码 给出解决办法
  1. <html>
  2. <head>
  3. <title>Iframe</title>
  4. </head>
  5. <body>
  6. <script type="text/javascript">
  7. document.domain = 'a.com';
  8. var iframe = document.createElement("iframe");
  9. document.body.appendChild(iframe);
  10. if(/msie/i.test(navigator.userAgent)){
  11.     try{
  12.         iframe.contentWindow.document;
  13.     } catch (e) {
  14.         iframe.onload = function() {
  15.             console.log(iframe.contentWindow.document.location);
  16.             iframe.onload = null;
  17.         }
  18.         iframe.src = "javascript:void((function(){document.open();document.domain='"+ document.domain + "';document.close()})())";
  19.     }
  20. }
  21. </script>
  22. </body>
  23. </html>
复制代码



作者: 八号    时间: 2013-11-15 14:26
jQuery form 插件 调试代码

  1. $.fn.ajaxSubmit.debug = true;

  2. $(document).ajaxError(function(ev,xhr,o,err) {
  3.     alert(err);
  4.     if (window.console && window.console.log) console.log(err);
  5. });
复制代码

作者: 八号    时间: 2013-11-15 21:16
另一种解决方法是在服务器端输出对应的 document.domain修改文件域
如 ajaxSubmit之前 文件域被改  document.domain = 'tkxxd.com';

那么服务端可以输出相应的代码,但需要判断  $_SERVER['HTTP_X_REQUESTED_WITH']

  1. <?php
  2. $result = json_encode($result);
  3. header("Content-Type: text/html; charset=utf-8");
  4. if ($_SERVER['HTTP_X_REQUESTED_WITH'] != 'XMLHttpRequest') {
  5.     $result = '<html><head><script>document.domain = "tkxxd.com";</script></head><body>' . $result . '</body></html>';
  6. }
  7. echo $result;
  8. exit;
复制代码





欢迎光临 天空小小岛技术网站 (http://tkxxd.net/) Powered by Discuz! X3.1