Posted on 2007-10-18 11:53
hilor 閱讀(4002)
評論(0) 編輯 收藏 所屬分類:
common
javascript和JAVA一樣,一些特殊字符需要轉(zhuǎn)義
特別是在一些JSP網(wǎng)頁的開發(fā)中,好多程序員經(jīng)常會忘掉這點(diǎn),
例:
1 <% List textList = (List)request.getAttribute("textList"); %>
2 <script>
3 <!--
4 var txtList = new Array();
5 <% for ( int i = 0 ; i < textList.size() ; i++) { %>
6 txtList[<%=i%>] = "<%=textList.get(i)%>";
7 <% } %>
8 -->
9 </script>
這段JS就存在問題,未對特殊符號進(jìn)行處理.有特殊符號的情況下有可能報JSERROR
JAVASCRIPT中需要轉(zhuǎn)義的有:
轉(zhuǎn)義序列 |
字符 |
\b |
退格 |
\f |
走紙換頁 |
\n |
換行 |
\r |
回車 |
\t |
橫向跳格 (Ctrl-I) |
\' |
單引號 |
\" |
雙引號 |
\\ |
反斜杠 |
此外,對/符號我覺得也有必要進(jìn)行處理,因?yàn)橄?--></script> 這樣的字符串也會使SCRIPT出錯.
下面提供一個比較實(shí)用java的方法,做這個特殊符號的處理:
1 <% List textList = (List)request.getAttribute("textList"); %>
2 <script>
3 <!--
4 var txtList = new Array();
5 <% for ( int i = 0 ; i < textList.size() ; i++) { %>
6 txtList[<%=i%>] = "<%=JavaScriptUtils.javaScriptEscape(textList.get(i))%>";
7 <% } %>
8 -->
9 </script>