Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

javascript variable that contains </script>

I need a little assistance. I have to create a javascript string that contains more javascript that is then written to a div tag in the parent window. The code is as follows:

<script language="javascript" type="text/javascript">
var jstr2 = '';
jstr2 += '<script language="javascript">
';
jstr2 += 'function doPagingProducts(str) {
';
jstr2 += 'document.frmPagingProducts.PG.value = str;
';
jstr2 += 'document.frmPagingProducts.submit();
';
jstr2 += 'return false;
';
jstr2 += '}
';
jstr2 += '</script>
';
jstr2 += '
';
</script>

However the closing script tag in the created string actually close the javascript and I get errors such as:

Error: unterminated string literal
Line: 135, Column: 9 ( The </script> line before the end of the string.)
Source Code:
jstr2 += '

Is there any way I can prevent this issue..?

Many thanks for all your help.

Best Regards, Paul


edit I finally solved this problem by extracting the final </script> from the javascript string. I added a end tag where the script shows. Its messy, but it works. Many thanks for all your comments.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The SCRIPT tag is content agnostic, so the parser just keeps running through the content until it finds a /SCRIPT sequence. When it does, it passes the content it's found to the JS environment for evaluation. That gives you your unterminated literal error because the sent content ends where your /SCRIPT begins. (There is no terminating quote mark to be found for the JS parser).

Escaping the slash with backslash

jstr2 += "</script>";

or some other work-around hack breaks the trigger point in the sequence here and solves this problem (but still leaves you with some very dubious code).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...