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

懵懂的女人 提交于 2019-12-09 19:30:37

问题


I got problem with line breaks in a textarea.

I get the text with .val() function:

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

This is my ajax request

$.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?


回答1:


When you pass a string as the data parameter, you must URL encode it like this:

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

If you pass the parameters as an object, jQuery takes care of encoding the data:

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



回答2:


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




回答3:


Is not that a known issue? http://api.jquery.com/val/

The workaround is using valHooks as explained in the Note section.



来源:https://stackoverflow.com/questions/5534928/jquery-val-not-returning-line-breaks-in-a-textarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!