javascript iFrame src 属性和相对 URL 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30268083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 11:58:32  来源:igfitidea点击:

iFrame src property and relative URLs not working

javascriptjqueryhtmliframe

提问by SpaceCowboy74

I have a web page that has an iFrame in it with a definition in the HTML like the following:

我有一个网页,其中包含一个 iFrame,在 HTML 中定义如下:

<iframe id="page_is_fresh"  src="~/HTML/fresh.html" style="display: none"></iframe>

My site is running under a subfolder /Marketing so all urls are something like http://myserver/Marketing/SomeFolder/someitem.html

我的网站在子文件夹 /Marketing 下运行,因此所有网址都类似于http://myserver/Marketing/SomeFolder/someitem.html

I have javascript to change the src of my iframe when an item on the form changes.

当表单上的项目更改时,我有 javascript 来更改 iframe 的 src。

    $('#page_is_fresh').attr('src', '/HTML/stale.html');

The problem is, this makes the url http://myserver/HTML/stale.html

问题是,这使得 url http://myserver/HTML/stale.html

I tried using '~/HTML/stale.html' and that gives me http://myserver/Marketing/SomeFolder/~/HTML/stale.htmlwhich doesn't work either.

我尝试使用 '~/HTML/stale.html' ,这给了我http://myserver/Marketing/SomeFolder/~/HTML/stale.html这也不起作用。

How can I get it to give me http://myserver/Marketing/HTML/stale.htmlwithout having to hard code the /Marketing part in?

我怎样才能让它给我http://myserver/Marketing/HTML/stale.html而不必硬编码 /Marketing 部分?

采纳答案by deflator

Use ../HTML/stale.htmlinstead of ~/HTML/stale.htmlor /HTML/stale.htmlin your javascript.

使用../HTML/stale.html代替~/HTML/stale.html/HTML/stale.html在您的 javascript 中。

The server considers ~to be a directory in the way you formatted it.

服务器认为~是您格式化的目录。

../lets the server know it needs to start one directory up

../让服务器知道它需要启动一个目录