首页 > 解决方案 > 在iframe中使用`window.top.$`发送ajax请求,但是referer不是iframe src的url

问题描述

有两个 html 文件,一个index.htmlinner.html.

** index.html **

<html>
<body>
<script src="./node_modules/jquery/dist/jquery.js"></script>
<iframe src="./inner.html" frameborder="1"></iframe>
</body>
</html>

它引用了jquery。

** 内部.html **

<html>
<body>
<input type="button" id="button" value="Get Data by AJAX">
<script src="./inner.js"></script>
</body>
</html>

** 内部.js **

const $ = window.top.$

$('#button', window.document).click(function () {
    $.ajax({
        url: '/data.json',
        success: function (data) {
            console.log(data)
        },
        context: this
    })
})

在服务器端,我将打印 header referer

打开 index.html 的 url 是:http://localhost:3000.

我发现当我在 inner.html 中使用$from发出 ajax 请求时window.topreferer在 server 中打印的是http://localhost:3000,这是外部页面的 url。

我希望成为 iframe 的 url http://localhost:3000/inner.html,但是如果我坚持使用来自window.top.

PS:如果我将代码<script src="./node_modules/jquery/dist/jquery.js"></script>从移动index.htmlinner.html,并用于window.$在 inner.html 中发送 ajax 请求,那么引用者就是我所期望的:http://localhost:3000/inner.html

这是我项目的一个简化demo,其中我们要使用平台提供的jquery,即window.top.$

标签: javascriptjqueryajaxiframereferer

解决方案


推荐阅读