简体   繁体   中英

jquery text area problem

i have one text area

        <textarea name="message" id="message" class="text_field" style="height:200px; width:500px"></textarea>

if i type data in the text area like this

        hello
        this is my test message

        bye
        'abc'

i use following statement to get data from text area

     var message = $('#message').attr('value');

i pass this value to other php file like

      var data = {message:message};
 $.ajax({
 type: "POST",
 url: "show.php",
 data: data,
 etc

when i see data in post value firebug in show exactly i type the data (with new lines & spaces etc) and in php file

          $message=$_POST['message'];

           $Content = file_get_contents($temp_page);
           $Content = str_replace('%%a%%', $message, $Content);

now when i use

             echo $Content

i get all the text in one line not exact i type in text area...

          hello this is my test message bye 'abc'

Thanks

That is because browsers don't print newlines outside textareas or other elements that are defined to print the output as is, for example <pre> .

You need to use echo nl2br($Content); to substitute newlines with <br /> elements, which is the equivalent of a newline in (x)HTML.

If you're echoing straight to the browser, try viewing the source of the page. You may find that the browser is interpreting the text as HTML, in which case it will collapse all your whitespace and newlines. Viewing the source should in theory show you what you originally typed, with newlines, extra space etc.

Think about what happens if you just typed in some HTML source like this:

<p>
  Hello there.
     This is 
  my

       HTML

  source, and I hope

                     you

      like it.
</p>

What does that look like? Right — the browser will treat all those newlines as simple whitespace, and collapse it all as it lays out the non-whitespace characters.

When you dump out the textarea contents (by the way: get the value with $('#whatever').val() ) you're doing the same thing. If you want to preserve the formatting, well, that can be a headache. You can try putting it in a <pre> block, or you may have to explicitly find the newlines and convert them to <br> elements.

edit: See @Tatu's answer for the php function you want.

IF you right click and click 'View Source' (or some close equivalent), you should see the properly formatted text. This is due to the way that HTML works. Even if you write the following HTML:

hello
this is my test message

bye
'abc'

The output will be inline. You have to write
after each line, or wrap the text in a <pre> tag.

也许您可以尝试:

nl2br($Content);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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