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

时间:2022-03-14 18:18:09

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:

$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. How do I fix this?

如果我将变量messageBody插入另一个div元素,我看不到任何\ n这是正常的。我该如何解决?

3 个解决方案

#1


14  

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
    }
});

#2


0  

You may want to look at PHP's nl2br function. Newlines characters do not render in the browser, so you have to replace them with line breaks.http://us.php.net/nl

你可能想看看PHP的nl2br函数。换行符不会在浏览器中呈现,因此您必须使用换行符替换它们.http://us.php.net/nl

#3


0  

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,如注释部分所述。

#1


14  

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
    }
});

#2


0  

You may want to look at PHP's nl2br function. Newlines characters do not render in the browser, so you have to replace them with line breaks.http://us.php.net/nl

你可能想看看PHP的nl2br函数。换行符不会在浏览器中呈现,因此您必须使用换行符替换它们.http://us.php.net/nl

#3


0  

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,如注释部分所述。