StringBuilder 中的 document.write ?

发布于 2024-09-18 05:49:18 字数 521 浏览 4 评论 0原文

我在 ashx 文件中使用 StringBuilder 来返回 javascript。除了一行之外,一切都工作正常...

javascript.Append("document.write(\"<script id=__ie_onload defer \" + \"src=javascript:void(0)><\/script>\");");

为了便于阅读,这里是未转义的版本:

document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");

如果我注释掉这一行,我的 ashx 文件就像一个魅力!但如果我把它保留在里面,它甚至不会运行。在 StringBuilder 中使用 document.write 语句是否有某种限制?或者,是否有更好的方法从 .NET 中编写 Javascript?由于需要使用服务器变量,它必须来自 .NET。

I am using a StringBuilder in an ashx file to return javascript. It all works fine, except for one line...

javascript.Append("document.write(\"<script id=__ie_onload defer \" + \"src=javascript:void(0)><\/script>\");");

For readability, here is the unescaped version:

document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");

If I comment out this line, my ashx file works like a charm! If I keep it in, though, it won't even run. Is there some sort of restriction on using a document.write statement in a StringBuilder? Alternatively, is there a better way to write out Javascript from within .NET? It has to be from .NET due to the need for using server variables.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

岁月如刀 2024-09-25 05:49:18

您的结束 script 标记中存在无法识别的转义序列。 \/ 不是有效的转义序列。您可能想要:

javascript.Append("document.write(\"<script id=__ie_onload defer \" + \"src=javascript:void(0)></script>\");");

或者,如果您确实想要该 \/ 序列,则双​​重转义 \

javascript.Append("document.write(\"<script id=__ie_onload defer \" + \"src=javascript:void(0)><\\/script>\");");

作为调试提示,如果您的工具为您提供的反馈如此糟糕,您甚至看不到编译错误,请尝试创建包含有问题的代码的测试应用程序。我将您的代码复制到控制台应用程序中,例如:

static void Main(string[] args)
{
    var javascript = new StringBuilder();
    javascript.Append(...
    Console.Write(javascript);
}

...我在编译时立即看到了问题:

无法识别的转义序列

...问题序列带有下划线。

You have an unrecognized escape sequence in your closing script tag. \/ is not a valid escape sequence. You probably want:

javascript.Append("document.write(\"<script id=__ie_onload defer \" + \"src=javascript:void(0)></script>\");");

Or if you really want that \/ sequence, then doubly-escape the \:

javascript.Append("document.write(\"<script id=__ie_onload defer \" + \"src=javascript:void(0)><\\/script>\");");

As a debugging tip, if your tools provide you with such poor feedback that you can't even see compilation errors, try creating a test application containing the problematic code. I copied your code into a console application, something like:

static void Main(string[] args)
{
    var javascript = new StringBuilder();
    javascript.Append(...
    Console.Write(javascript);
}

...and I saw the problem immediately on compilation:

Unrecognized escape sequence

...with the problem sequence underlined.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文