简体   繁体   English

在JavaScript中将ColdFusion变量与换行符一起使用

[英]Using ColdFusion variable with line breaks in JavaScript

I have a text area that accepts line breaks. 我有一个接受换行符的文本区域。 The content of that text area is saved in a coldfusion variable (lets call it #fieldVal# ). 该文本区域的内容保存在Coldfusion变量中(我们称其为#fieldVal# )。 So, my variable contents look like 所以,我的可变内容看起来像

textline 1
textline 2

Later on, I use that variable in JavaScript 稍后,我在JavaScript中使用该变量

document.all.fieldName.value = "#fieldVal#";

However, when the JavaScript hits the page, it looks like this: 但是,当JavaScript命中页面时,它看起来像这样:

document.all.fieldName.value = "textline 1
textline 2";

and the script breaks because the first line doesn't end in a semicolon. 并且脚本中断,因为第一行不以分号结尾。

I tried setting a JavaScript variable to the ColdFusion text then doing a replace() , but I still hit the same issue with the line not ending correctly. 我尝试将JavaScript变量设置为ColdFusion文本,然后执行replace() ,但是由于行未正确结束,我仍然遇到相同的问题。

I think I'm missing something obvious but I am just not seeing it. 我认为我缺少明显的东西,但我只是没有看到。 Can someone tell me what I'm missing here? 有人可以告诉我我在这里想念的吗?

Use the JSStringFormat() function. 使用JSStringFormat()函数。 It is designed to escape meta characters in JavaScript 它旨在转义JavaScript中的元字符

Escapes special JavaScript characters, such as single-quotation mark, double-quotation mark, and newline. 转义特殊的JavaScript字符,例如单引号,双引号和换行符。

https://wikidocs.adobe.com/wiki/display/coldfusionen/JSStringFormat https://wikidocs.adobe.com/wiki/display/coldfusionen/JSStringFormat

document.all.fieldName.value = "#JSStringFormat( fieldVal )#";

If you're using ColdFusion 10+ or Lucee Server, use EncodeForJavaScript() . 如果您使用的是ColdFusion 10+或Lucee Server,请使用EncodeForJavaScript()

https://wikidocs.adobe.com/wiki/display/coldfusionen/EncodeForJavaScript https://wikidocs.adobe.com/wiki/display/coldfusionen/EncodeForJavaScript

Option 1 选项1

document.all.fieldName.value = "#Replace(trim(fieldVal), chr(10) & chr(13), ' ', 'ALL')#"; 

Option 2 (Possible that the same issue occur in this too.) 选项2 (也可能在其中发生相同的问题。)

Try using ToScript() 尝试使用ToScript()

ToScript(fieldVal, valueVar)

Toscript initializes a variable with the coldfusion variable value and you can use like any JS global variable. Toscript使用Coldfusion变量值初始化变量,您可以像使用任何JS全局变量一样使用。

document.all.fieldName.value = valueVar;

Option 3 (If you need in HTML form) 选项3 (如果需要HTML格式)

Use coldfusion function ParagraphFormat() which changes line breaks into <br/> . 使用Coldfusion函数ParagraphFormat()将换行符更改为<br/>

I stumbled upon a code snippet that worked. 我偶然发现了一个有效的代码段。 Its a bit...convoluted, but it works. 有点...令人费解,但它可以工作。

document.all.fieldName.value = "#Replace(Replace(URLDecode(Replace(Replace(URLEncodedFormat(fieldVal), "%0D", " ", "ALL"), "%0A", "", "ALL")),CHR(34),"", "ALL"),CHR(39),"", "ALL")#"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM