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/javascri开发者_如何转开发pt">
<![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' . '&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 .
.
精彩评论