简体   繁体   English

Jquery .val()没有在textarea中返回换行符

[英]Jquery .val() not returning line-breaks in a textarea

I got problem with line breaks in a textarea. 我在textarea中遇到了换行问题。

I get the text with .val() function: 我用.val()函数获取文本:

var messageBody = $('#composeInput').val();

This is my ajax request 这是我的ajax请求

$.ajax({
    url: 'serverScripts/messages/addMessage.php',
    data: 'messageBody='+messageBody+'&invitedJSONText='+invitedJSONText,
    success: function(){
        //Do something
    }
});

And PHP: 和PHP:

$messageBody = nl2br(mysql_real_escape_string($_GET['messageBody']));

The text: 文本:

Hi! 嗨!

How are you? 你好吗?

Becomes: 变为:

Hi! 嗨! How are you? 你好吗?

If I insert the variable messageBody to an another div-element I can't see any \\n is this normal. 如果我将变量messageBody插入另一个div元素,我看不到任何\\ n这是正常的。 How do I fix this? 我该如何解决?

When you pass a string as the data parameter, you must URL encode it like this: 传递字符串作为数据参数时,必须对其进行URL编码,如下所示:

'messageBody=' + encodeURIComponent(messageBody) + '&invitedJSONText=' + encodeURIComponent(invitedJSONText)

If you pass the parameters as an object, jQuery takes care of encoding the data: 如果将参数作为对象传递,jQuery负责编码数据:

$.ajax({
    url: 'serverScripts/messages/addMessage.php',
    data: {
        messageBody: messageBody,
        invitedJSONText: invitedJSONText
    },
    success: function (data, textStatus, jqXHR) {
        $("#foo").html(data); // <-- did something
    }
});

Is not that a known issue? 这不是一个已知问题吗? http://api.jquery.com/val/ http://api.jquery.com/val/

The workaround is using valHooks as explained in the Note section. 解决方法是使用valHooks,如注释部分所述。

You may want to look at PHP's nl2br function. 你可能想看看PHP的nl2br函数。 Newlines characters do not render in the browser, so you have to replace them with line breaks.http://us.php.net/nl Newlines字符不会在浏览器中呈现,因此您必须使用换行符替换它们.http://us.php.net/nl

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

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