【发布时间】:2015-11-23 15:33:31
【问题描述】:
我正在尝试在我的网页中包含一个小部件。小部件的代码是用 ajax 动态加载的(因为它经常变化,我需要从服务器更新它),它看起来像这样......
<a class="e-widget" href="https://gleam.io/0oIpw/contest-widget" rel="nofollow">This is a Widget!</a>
<script type="text/javascript" src="https://js.gleam.io/e.js" async="true"></script>
在加载时,我在控制台中收到以下错误...
OPTIONS https://js.gleam.io/e.js 404 (Not Found)
XMLHttpRequest cannot load https://js.gleam.io/e.js. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://localhost:8443' is therefore not allowed access. The response had HTTP status code 404.
如果我删除了为小部件加载数据的 ajax 调用,而是直接插入小部件,我不会收到相同的错误并且小部件工作正常。
我已阅读并认为这是由于同源策略 (SOP),所以我现在想知道规避该策略的最佳方法。
我已经阅读了Ways to circumvent the same-origin policy 的帖子,但不幸的是在这种情况下没有发现它有帮助。
既然 CORS 是在服务器端完成的(我认为?)并且 JSONP 不安全,那么创建代理是最好的选择吗?
非常感谢您的帮助。我花了好几个小时研究这个,但我仍然感到困惑。
编辑添加代码以获取更多信息:
点击命令链接时,页面信息通过ajax加载如下:
<h:commandLink action="#{redeemPerk.getDisplay(display.displayId)}" >
<h:graphicImage value="#{display.imgUrl}" styleClass="display-icon"/>
<f:ajax event="click" execute="@form" render="redeem-display-data-reveal" listener="#{redeemPerk.getDisplay(display.displayId)}" onevent="handleAjax"/>
</h:commandLink>
这会渲染显示小部件的区域,看起来像...
<div class="reveal-modal-background hidden">
<h:form id="redeem-display-data-reveal">
<h:panelGroup rendered="#{display.type == 'WIDGET'}">
<a class="e-widget" href="https://gleam.io/0oIpw/contest-widget" rel="nofollow">This is a Widget!</a>
<script type="text/javascript" src="https://js.gleam.io/e.js" async="true"></script>
</h:form>
</div></h:panelGroup>
第二个代码块与第一个代码块位于一个单独的文件中。重申一下,如果我删除 ajax 调用并直接加载数据,小部件可以正常工作。
【问题讨论】:
-
您没有向我们展示任何实际的 Javascript。
-
我想这就是我感到困惑的原因。该小部件应仅基于这些脚本标签工作,因此我不确定如何合并 JSONP
-
这看起来像是小部件中的错误。
-
我也想知道是不是这样,但如果我不先用 ajax 加载页面,它就可以工作,这让我不一样
标签: javascript ajax widget same-origin-policy