Jquery .val() not returning line-breaks in a textarea
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?
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
}
});
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
Is not that a known issue? http://api.jquery.com/val/
The workaround is using valHooks as explained in the Note section.
精彩评论