简体   繁体   中英

Xhtml write URL,which one is correct?

I need to write a url within a javascript, but do not know if I should write & for & symbol.

<script type="text/javascript">
<![CDATA[
 var link = 'http://example.com/query?id=1' . '&ref=' . document.referrer;
 ]]></script>

Or

<script type="text/javascript">
<![CDATA[
 var link = 'http://example.com/query?id=1' . '&amp;ref=' . document.referrer;
 ]]></script>

Inside CDATA , there's no need to escape & and it should not be escaped in the resulting URL, so the first one is correct.

Correct would be

<script type="text/javascript">
<![CDATA[
 var link = 'http://example.com/query?id=1' + '&ref=' + encodeURIComponent(document.referrer);
]]></script>

You must not XML-escape characters in CDATA sections. That's the whole point of using them in the first place.

But note the URL-encoding that you forgot. And JavaScript string concatenation works with + , not . .

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