后台的字符串输出成js的变量时,需要进行转码,例如
var a="<%=serverStr%>";
当serverStr里有双引号时,会打乱js的双引号。
对于转码
如果是jsp,请使用以下类里的jsEncoder来完成
即:
var a="<%=CommStr.jsEncoder(serverStr)%>";
---------------------------------------------------
/*
 * Created by Seamus
 * Updated on 2004-10-21 by JK
 *
 */
package com.jk.util;public class  CommStr
{
  /**
  *replace the old string to new string in the given destination string.
  */
  public static java.lang.String strReplace(java.lang.String destStr, java.lang.String oldStr, java.lang.String newStr)
  {
    if(destStr==null)
      return "";
    String tmpStr = destStr;
    int foundPos = tmpStr.indexOf(oldStr);
    while (foundPos>=0)
    {
      tmpStr = tmpStr.substring(0,foundPos) + newStr + tmpStr.substring(foundPos + oldStr.length(),tmpStr.length());
      foundPos = tmpStr.indexOf(oldStr,foundPos+newStr.length());
    }
    return tmpStr;
  }  /**
  *Encode for HTML.
  */
  public static String htmlEncoder(String str)
  {
    if(str==null || str.equals(""))
      return "";
    String res_str;
    res_str=strReplace(str,"&","&amp;");
    res_str=strReplace(str," ","&nbsp;");
    res_str=strReplace(str,"<","&lt;");
    res_str=strReplace(str,">","&rt;");
    res_str=strReplace(str,"\"","&quot;");
    res_str=strReplace(str,"'","&#039;");
    return res_str;
  }  /**
  *Encode for HTML-Text.
  */
  public static String htmlTextEncoder(String str)
  {
    if(str==null || str.equals(""))
      return "";
    String res_str;
    res_str=strReplace(str,"&","&amp;");
    res_str=strReplace(str,"<","&lt;");
    res_str=strReplace(str,">","&rt;");
    res_str=strReplace(str,"\"","&quot;");
    res_str=strReplace(str,"'","&#039;");
    res_str=strReplace(str," ","&nbsp;");
    res_str=strReplace(str,"\r\n","<br>");
    res_str=strReplace(str,"\r","<br>");
    res_str=strReplace(str,"\n","<br>");
    return res_str;
  }  /**
  *Encode for URL.
  */
  public static String urlEncoder(String str) {
    return java.net.URLEncoder.encode(str) ;
  }  /**
  *Encode for XML.
  */
  public static String xmlEncoder(String str)
  {
    if(str==null || str.equals(""))
      return "";
    String res_str;
    res_str=strReplace(str,"&","&amp;");
    res_str=strReplace(res_str,"<","&lt;");
    res_str=strReplace(res_str,">","&gt;");
    res_str=strReplace(res_str,"\"", "&quot;");
    res_str=strReplace(res_str,"\'", "&acute;");
    return res_str;
  }  /**
  *Encode for SQL.
  */
  public static String sqlEncoder(String str)
  {
    if(str==null || str.equals(""))
      return "";
    String res_str;
    res_str=strReplace(str,"'","''");
    return res_str;
  }  /**
  *Encode for Javascript.
  */
  public static String jsEncoder(String str)
  {
    if(str==null || str.equals(""))
      return "";
    String res_str;
    res_str=strReplace(str,"'","\\'");
    res_str=strReplace(str,"\"","\\\"");
    res_str=strReplace(str,"\r\n","\\\n");
    res_str=strReplace(str,"\n","\\\n");
    res_str=strReplace(str,"\r","\\\n");
    return res_str;
  }}