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条)

报告相同问题?

悬赏问题

  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败