简体   繁体   English

如何阻止Internet Explorer重写我的文本?

[英]How do I prevent internet explorer from rewriting my text?

I have a javascript variable that contains an url, populated by outputting a script tag from php. 我有一个包含url的javascript变量,通过从php输出脚本标记来填充。 The intention is to change the webpage to that url under certain circumstances. 目的是在某些情况下将网页更改为该网址。

var url = "/somepage?q=3&region=1";

The problem is that the url contains the sequence "&reg" which internet explorer changes to "®" without being asked. 问题是网址包含序列“&reg”,Internet Explorer在没有被询问的情况下变为“®”。

I've tried escaping the whole url with htmlspecialchars, which breaks other browsers. 我已经尝试使用htmlspecialchars转义整个网址,这打破了其他浏览器。 Turning off quirks mode might help, but it's not an option with the current system. 关闭怪癖模式可能有所帮助,但它不是当前系统的选项。 Adding to the script tag did nothing. 添加到脚本标记没有做任何事情。

edit: I figured out one solution, "escaping" the url with concatenation. 编辑:我想出了一个解决方案,用连接“转义”网址。

var url = '<?php implode( "&'+'", explode( '&', '/somepage?q=3&region=1' ) ); ?>';

I also realized I should probably mention how I change the page: 我也意识到我应该提一下如何更改页面:

document.location.href = url;

edit: Turns out I had an error in my script tag. 编辑:结果我的脚本标记出错了。 A minimal example that shows the same "problem": 显示相同“问题”的最小示例:

<script type="text/javascript" />
    var url = "/test?mode=preview&region=1";
</script>

The self-closing start tag is the important thing here. 自动关闭开始标记是重要的事情。

It should be var url = "/somepage?q=3&amp;region=1"; 它应该是var url = "/somepage?q=3&amp;region=1";

Always use &amp; 始终使用&amp; in URLs so the browser understands this a query separator and doesn't think it refers to some htmlentity (the problem here is IE doesn't care if the semicolon is present or not and assumes &reg should be &reg; ) 在URL中,所以浏览器理解这是一个查询分隔符,并不认为它引用某些htmlentity(这里的问题是IE不关心分号是否存在并假设&reg应该是&reg;

EDIT: the real context was added after I answered and as pointed out in the question itself and in comments, you shouldn't use &amp; 编辑:在我回答之后添加了真实的背景,正如问题本身和评论中指出的那样,你不应该使用&amp; if you intend to use the variable to redirect using some window.location 如果您打算使用某个window.location来重定向该变量

BUT, since we have PHP at hand, I would suggest using some PHP code like this if the javascript redirect is not part of some other complex script: 但是,由于我们手头有PHP,如果javascript重定向不是其他复杂脚本的一部分,我建议使用这样的PHP代码:

<?php
header('Location: http://domain/somepage?q=3&region=1');
exit();
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM