2

我試圖使用jQuery插件的形式進行跨域文件上傳表單的工作,但我不斷收到的螢火控制檯以下錯誤:jquery.form和跨域請求

Permission denied to access property 'document' 

它發生在下面的行jquery.form插件

403: var doc = frame.contentWindow ? frame.contentWindow.document : frame.contentDocument ? frame.contentDocument : frame.document; 

,如果我使用Safari瀏覽器,我得到這個錯誤:

Unsafe JavaScript attempt to access frame with URL http://s1.test-host/index.php/upload/start?is-async=1 from frame with URL http://test-host/index.php/main/. Domains, protocols and ports must match. 

喜歡本作的的HTML的外觀:

<form action="http://s1.test-host//index.php/upload/start" method="post" accept-charset="utf-8" id="upload-form" enctype="multipart/form-data"> 
    <input type="hidden" name="MAX_FILE_SIZE" value="1204000" /> 
     <label for="file-input">Input File</label> 
     <input type="file" name="file" value="" id="file-input" alt="Input File" /> 
     <input type="submit" name="upload" value="Convert" id="start-upload" /> 
    </form> 

的JavaScript看起來像這樣:

$(this).ajaxForm ({ 
    beforeSubmit: onFileFormSubmit,  // pre-submit callback 
    success:  onFileFormSubmitEnd, // post-submit callback 
    resetForm: true,    // reset the form after successful submit 
    dataType:  'json',   // force response type to JSON 
    iframe:  true    // force the form to be submitted using an iframe 
}); 

目標PHP頁面有這樣的:

if ($_SERVER['HTTP_ORIGIN']) { 
     header('Access-Control-Allow-Origin: *'); 
     header('Access-Control-Allow-Methods: POST, GET, OPTIONS'); 
     header('Access-Control-Max-Age: 1000'); 
     header('Access-Control-Allow-Headers: Content-Type'); 
    } 
    ... // Usual upload handling code 

,但似乎沒有奏效。我甚至試圖將'dataType'改爲'jsonp',並且也改爲從'post'改爲'get',但所有這些都無濟於事,我仍然得到相同的錯誤。如果我查看服務器,文件確實會上傳,但javascript無法調用成功功能。

谷歌搜索後,我發現可能有其他解決方案,如'JQuery文件上傳'或'plupload',但我真的需要一些簡單的東西,我不想使用HTML5功能。

+0

你可以上傳到同一個域,並使用服務器發送到其他域?問題是AJAX不做文件上傳,所以使用隱藏的iframe,然後響應是另一個域,所以沒有iframe訪問 – charlietfl

回答

1

文件上傳插件使用iframe上傳文件。既然你不能在沒有正確的CORS頭文件的情況下發布跨域,並且你不能提供CORS頭文件到iframe,這是不可能的。最好的選擇是將其發佈到您的服務器上,然後根據需要使用服務器端代碼將其移動到跨域。

0

我知道你不想要什麼奇特的東西,但對於沒有完整XHR支持的瀏覽器中的跨域,我推薦使用jQuery-File-Upload插件。它使用iframe將文件上傳到另一個域。它需要更多的工作,但:

  • 您需要更改上傳服務器響應什麼插件expects
  • 你需要的地方上傳result.html在原始服務器獲得響應

如果你不想要UI的東西,你可以使用基本的版本的插件。