javascript中未终止的字符串常量错误

iRu*_*ner 0 java google-calendar-api dom-events

我正在研究Google Calendar api.每当我创建任何事件并输入具有新行的事件的描述时,它会给出类似"Unterminated String constant"的错误.我将事件描述从java传递给javascript.So如何格式化具有新行的字符串?

我的代码是

 var EventDescription='<% =eventDetails.getEventDescription(eventIndex)%>'

    eventDetails -java class 
    getEventDEscription -Method to get the Description of event.
    eventIndex - no of the event whoes Description is needed .
Run Code Online (Sandbox Code Playgroud)

它正常工作.只有在描述有新线时才给出错误.

JB *_*zet 5

尝试将自己想象为JSP容器,然后将其想象为JavaScript解释器.或者只是查看生成的HTML页面的源代码.

这条线

var EventDescription='<% =eventDetails.getEventDescription(eventIndex)%>'
Run Code Online (Sandbox Code Playgroud)

由JSP容器解释.所以eventDetails.getEventDescription(eventIndex)执行,并且该方法调用的结果放在回应.假设结果由两行组成:

line 1
line 2
Run Code Online (Sandbox Code Playgroud)

所以生成的JavaScript代码是:

var EventDescription='line1
line 2'
Run Code Online (Sandbox Code Playgroud)

这是无效的JavaScript代码.正确的JavaScript代码将是

var EventDescription='line1\nline 2'
Run Code Online (Sandbox Code Playgroud)

因此,您需要在将Java方法调用的结果放入响应之前对其进行JavaScript转义.查看Apache commons-lang StringEscapeUtils.escapeEcmaScript()方法.