当来自MySQL的值包含换行符时,如何使用jQuery设置文本区域的内容 [英] Using jQuery how can I set the contents of a textarea when the value from MySQL contains newlines
问题描述
为了保持代码整洁,我使用jQuery默认设置表单的每个元素.
To keep my code clean I am defaulting each of the elements of a form with jQuery.
即我的表单包含这样的元素.
i.e My form contains elements like this..
<input name="mobile" id="mobile" type="text" />
在我自己的javascript文件中,我从MySQL读取数据,然后在加载表单后使用jQuery对其进行设置.
In my separate javascript file, I read data from MySQL, then use jQuery to set it, after the form is loaded..
$('#mobile').val('07845 887766');
从MySQL读取此值,然后在PHP中生成类似的代码.
this value is read from MySQL and I generate the code like this, in PHP..
echo "\n $('#mobile').val('".$user['mobile']."');";
这很好,但是问题出在有textarea字段时.
This works fine, but the problem lies when there is a textarea field..
<textarea name="notes" id="notes" ></textarea>
echo "\n $('#notes').html('TEST');";
这很好用,但是当我用数据库中的数据(可能包含换行符)替换它时,出现了JavaScript错误.
This works fine, but when I replace it with the data from a database, which can contain newlines, I get a javascript error.
echo "\n $('#notes').html('".$user['notes']."');";
这可能会产生此代码(实际值...)
This could produce this code (Actual values...)
$("#notes").html("INSERT INTO action (
inputdate,
)
VALUES ()");
哪个给出错误. 未终止的字符串文字"
Which gives an error. "unterminated string literal"
推荐答案
未终止的字符串文字
您收到此消息是因为在Javascript中,文字字符串不能跨多行.
You're getting this message because in Javascript you can't span literal strings across multiple lines.
您需要做的是用字符\r\n
替换$user['notes']
中的换行符,以便所有字符串都在一行上,然后<textarea>
输入将正确显示新项目中的每个项目.线.
What you need to do is replace newlines in $user['notes']
with the characters \r\n
so all the string is on one line then the <textarea>
input will correctly show each item on a new line.
让我们使用json_encode
来帮助我们避免Javascript不喜欢的任何讨厌的字符.
Let's use json_encode
to help us also escape any nasty characters which Javascript won't like.
// This will convert to be Javascript friendly.
// Output string will be enclosed in quotes " "
$notes_str = json_encode($user['notes']);
echo "\n $('#notes').html(" . $notes_str . ");";
这篇关于当来自MySQL的值包含换行符时,如何使用jQuery设置文本区域的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!