使用js / jsp中的格式符号设置字符串值

时间:2016-12-14 15:57:00

标签: javascript jsp

我在jsp页面上:

$('.image').click(function() {
    var alt = $(this).attr('alt');
    $('#article_desc').append(alt);
});

如果消息相同:

<script type="application/javascript">
    var test = {};
    test.id = ${docId};
    test.message = ${message};
</script>

我会在页面中收到错误:'hello world'

如何在js中设置字符串值?如果值为"Uncaught SyntaxError: Invalid or unexpected token"\n或其他格式符号

1 个答案:

答案 0 :(得分:0)

Glassfish4服务器上的示例。

以下JSP:

<!DOCTYPE html>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>initJsObject</title>
</head>
<body>
<!-- prepare attributes, just for testing -->
<c:set var="docId" value="123"></c:set>
<c:set var="message" value="'hello world'"></c:set>
<c:set var="lines" value="'line1\nline2'"></c:set>
<c:set var="backslashN" value="'\\\\\n'"></c:set>

<textarea id="txt" style="height: 200px; width: 200px;"></textarea>

<script type="text/javascript">
    var test = {};
    test.id = ${docId};
    test.message = ${message};
    test.lines = ${lines};
    test.backslashN = ${backslashN};
    console.log(test);

    document.getElementById("txt").value += "id: " + test.id + "\n";
    document.getElementById("txt").value += "message:" +  test.message + "\n\n";
    document.getElementById("txt").value += "lines:\n"+ test.lines + "\n\n";
    document.getElementById("txt").value += "backslashN: ("+ test.backslashN + ")\n\n";
</script>
</body>
</html>

生成html:

<!DOCTYPE html>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>initJsObject</title>
</head>
<body>
<!-- prepare attributes fot testing -->
<textarea id="txt" style="height: 200px; width: 200px;"></textarea>

<script type="text/javascript">
    var test = {};
    test.id = 123;
    test.message = 'hello world';
    test.lines = 'line1\nline2';
    test.backslashN = '\\n';
    console.log(test);

    document.getElementById("txt").value += "id: " + test.id + "\n";
    document.getElementById("txt").value += "message:" +  test.message + "\n\n";
    document.getElementById("txt").value += "lines:\n"+ test.lines + "\n\n";
    document.getElementById("txt").value += "backslashN: ("+ test.backslashN + ")\n\n";
</script>
</body>
</html>

浏览器输出:

  

id:123
  消息:你好世界

     

行:
  一号线
  第2行

     

反斜杠N:(\ n)

如您所见,属性字符串\n中的'line1\nline2'将被评估为新行 另一方面,如果您需要将sting \n显示为文本,则需要转义'\\\\\n'