简体   繁体   中英

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. 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?

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. This works fine in 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 "). 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. Do the actual frame rewrite operation in that scope:

window.parent.rewriteFormFrame(theHtml);

Where rewriteFormFrame function in the parent window looks something like this:

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. It's only way you can make this work in 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. If you depend on that, give jQuery a try.

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. 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.

Cheers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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