2011-02-28 135 views
8

我正在編寫一個使用JSONP從幾個不同源收集數據的HTML5應用程序。我用GET做的任何事情都完美無缺。我現在試圖發佈數據,並且遇到了一個有趣的障礙。我需要從我的應用程序發送數據到另一個應用程序從本地機器運行的應用程序。我正在嘗試編寫一個支持跨平臺的移動應用程序(考慮Pulse/Flipboard),因此代碼將始終從本地源運行。我的思維過程如下:跨源資源共享和文件://

所有我針對的瀏覽器是基於WebKit(新iPad,劇本,Android的) ,所以我想知道是否有相同的原產地政策代碼中的任何吱吱聲,我可以偷偷摸摸?也許使用iframe或postMessage的東西?

+0

「這會導致請求失敗(XmlHttpRequest錯誤:原始null不被Access-Control-Allow-Origin允許)」 - 它允許在當前瀏覽器中使用,所以問題已過時。 – inf3rno 2014-05-27 16:37:53

回答

9

,因爲它會變成,要做到這一點最簡單的方法是張貼到目標URL的iframe內。在大多數瀏覽器上使用相同的起始策略,您可以執行從一個域到另一個不相關域的HTTP POST。我通過向我的頁面添加一個iframe來解決問題,最初設置爲本地引導頁面。由於該頁面是從同一個域加載的,因此我可以通過腳本來控制它。我用它將表單發佈到我的目標站點,並調查結果以確定我的呼叫是否成功。這不是優雅,但它的作品。

1

這個Javascript庫幾乎肯定可以幫助你:

http://easyxdm.net/

easyXDM is a Javascript library that enables you as a developer to easily work around the limitation set in place by the Same Origin Policy, in turn making it easy to communicate and expose javascript API’s across domain boundaries.

..

At the core easyXDM provides a transport stack capable of passing string based messages between two windows, a consumer (the main document) and a provider (a document included using an iframe). It does this by using one of several available techniques, always selecting the most efficient one for the current browser. For all implementations the transport stack offers bi-directionality, reliability, queueing and sender-verification.

+1

感謝您的鏈接!這看起來很酷,但它並沒有特別符合我的要求。它看起來像現代基於webkit的瀏覽器,我使用的是我正在使用的移動平臺,他們對窗口通信的回答是HTML5 postMessage方法。這隻適用於應用程序的雙方發佈和接收消息。 – 2011-03-01 16:02:00