douqudi5282 2015-01-22 16:18
浏览 13
已采纳

怎么javascript发送空行到PHP?

I write a demo like this:

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript">
    window.onload = init;

    function init() {
        var btn = document.getElementById('submit');
        btn.onclick = function() {
            var str = document.getElementById('testText').value;
            alert(str);
            var xmlHttp = new XMLHttpRequest();
            var url = 'test.php?str=' + str;
            xmlHttp.onreadystatechange = function(){
                var str = xmlHttp.responseText;
                document.getElementById('testText').value = str.toLocaleUpperCase();

            };
            xmlHttp.open('GET', url, true);
            xmlHttp.send(null);
        };

    }
</script>
</head>
<body>
    <form action="test.php" method="POST">
        <textarea name="testText" id="testText" cols="30" rows="10"></textarea>
    <input type="button" value="submit" id="submit">
    </form>
</body>
</html>

It send a GET to server, and the php just return what it get, then js show it by uppercase(write this because of system ask me to write more detail of code) I write some text in textarea tag like

write some thing

write other thing

and output is

WRITE SOME THING WRITE OTHER THING

but I want to remain the blank lines, and expect output like this

WRITE SOME THING

WRITE OTHER THING

how should I do?

  • 写回答

2条回答 默认 最新

  • duande9301 2015-01-22 16:23
    关注

    When you send your data to PHP, you need to convert your text into URL format.

    var url = 'test.php?str=' + encodeURIComponent(str);
    

    When you output the PHP into an HTML document, you need to convert your text into HTML.

    Most elements do not treat whitespace as significant, so you need to convert the new lines into line break elements or do some other kind of formatting. (In general, you want to use something smarter, like Markdown syntax, but I'll use nl2br for this simplistic example):

    <div>
    <?php
        $data = $_GET['str'];
        $safe_data = htmlspecialchars($data);
        $formatted_data = nl2br($safe_data);
        echo $formatted_data;
    ?>
    </div>
    

    or, if you are outputting into an element with significant whitespace

    <textarea>
    <?php
        $data = $_GET['str'];
        $safe_data = htmlspecialchars($data);
        echo $safe_data;
    ?>
    </textarea>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?