简体   繁体   English

如何使用document.write()创建JavaScript来执行?

[英]How do I get JavaScript created with document.write() to execute?

I have a multi-frame layout. 我有一个多帧布局。 One of the frames contains a form, which I am submitting through XMLHttpRequest. 其中一个框架包含一个表单,我通过XMLHttpRequest提交。 Now when I use document.write() to rewrite the frame with the form, and the new page I am adding contains any javascript then the javascript is not exectuted in IE6? 现在,当我使用document.write()来重写带有表单的框架时,我添加的新页面包含任何javascript,那么javascript在IE6中没有被执行?

For example: 例如:

document.write("<html><head><script>alert(1);</script></head><body>test</body></html>");

In the above case the page content is replaced with test but the alert() isn't executed. 在上面的例子中,页面内容被替换为test但不执行alert()。 This works fine in Firefox. 这在Firefox中运行良好。

What is a workaround to the above problem? 针对上述问题的解决方法是什么?

Instead of having the JS code out in the open, enclose it in a function (let's call it " doIt "). 而不是将JS代码公开,将其包含在一个函数中(让我们称之为“ doIt ”)。 Your frame window (let's say it's name is "formFrame") has a parent window (even if it's not visible) in which you can execute JS code. 您的框架窗口(假设它的名称是“formFrame”)有一个父窗口(即使它不可见),您可以在其中执行JS代码。 Do the actual frame rewrite operation in that scope: 在该范围内执行实际的帧重写操作:

window.parent.rewriteFormFrame(theHtml);

Where rewriteFormFrame function in the parent window looks something like this: 父窗口中的rewriteFormFrame函数看起来像这样:

function rewriteFormFrame(html) {
    formFrame.document.body.innerHTML = html;
    formFrame.doIt();
}

Workaround is to programmatically add <script> blocks to head DOM element in JavaScript at Callback function or call eval() method. 解决方法是以编程方式将<script>块添加到JavaScript中的头部DOM元素的Callback函数或调用eval()方法。 It's only way you can make this work in IE 6. 这是你在IE 6中完成这项工作的唯一方法。

您可以在body标签中使用onload属性( <body onload="jsWrittenLoaded()"> )。

In short: You can't really do that. 简而言之:你不能真的这样做。 However JavaScript libraries such as jQuery provide functionality to do exactly that. 但是,jQuery之类的JavaScript库提供了完全相同的功能。 If you depend on that, give jQuery a try. 如果您依赖于此,请尝试jQuery。

Eval and/or executing scripts dynamically is bad practice. 动态评估和/或执行脚本是不好的做法。 Very bad practice. 非常糟糕的做法。 Very, very, very bad practice. 非常非常非常糟糕的做法。 I can't stress enough, how bad practice it is. 我不能强调,它的实践有多糟糕。

AKA.: Sounds like bad design. AKA:听起来很糟糕的设计。 What problem are you trying to solve again? 你想再次解决什么问题?

Another possible alternative is to use JSON, dynamically adding scripts references which will be automatically processed by browser. 另一种可能的替代方法是使用JSON,动态添加脚本引用,这些引用将由浏览器自动处理。

Cheers. 干杯。

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

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