Newline problem when writing to HTML using JavaScr

2020-04-16 05:03发布

I'm using regular textbox as a text input where the users wrties their comments. I then use JQuery and JSON to send data to the server and then insert it into the database.

When I want to display this text I use jQuery to download it prepare HTML and display it in the browser, but there are no new lines.

How can I keep any newlines entered by the user so that they are displayed in the browser?

EDIT:

The problem is that when I do alert $('.detailsCommentContent').val() I can see line breaks in the alert window, but when I then pass it as a GET argument:

insertComment.aspx?id=10&content= " + $('.detailsCommentContent').val() "

then in the url there are no signs of newLine :(

4条回答
爷的心禁止访问
2楼-- · 2020-04-16 05:14

where do you want to display the text? in a textarea or directly on the page?

if on the page you'll have to convert the newlines to <br/> tags when getting the text from the db and printing it to the page.

查看更多
Fickle 薄情
3楼-- · 2020-04-16 05:18

I beleive this is down to the encoding you are using. Difference between unicode and ascii or something similar. It's been a while since I worked on something like this but I think it boiled down to two options.

  1. match up the encoding on save and on load (we found that we had ascii on one and unicode on another).
  2. replace all new line character with an arbituary value when saving and swap it back when you load it.
查看更多
够拽才男人
4楼-- · 2020-04-16 05:20

Just do like this answer: keep formatting entered in asp.net textbox (carriage return, new line, etc)

theStringYouWantToFormat.Replace(char.ConvertFromUtf32(13),"<br/>")
查看更多
做个烂人
5楼-- · 2020-04-16 05:30

Before writing out the HTML using javascript to the page, make sure to replace all the newlines with <br /> tags. Here is a simple extension for string that will allow you to do it using javascript (source):

String.prototype.NewlineToBR = function() {
    return this.replace( /\r\n|\r|\n/g, br || '');
}

Usage:

var htmlString = newlineString.NewlineToBR();

Then just insert the new string into you HTML.

查看更多
登录 后发表回答