• AJAX发送和接收字符串(案例实战)

    在 JavaScript 中,为 XMLHttpRequest 对象设置 responseType='text',服务器端响应数据是一个字符串。

    【示例】下面示例设计一个在页面中显示一个文本框和一个按钮,在文本框中输入字符串之后,单击页面上的“发送数据”按钮,将使用 XMLHttpRequest 对象的 send() 方法输入字符串发送到服务器端,在接收到的服务器端响应数据后,将该响应数据显示在页面上。

    前台页面

    <script>
        function sendText () {
            var txt = document.getElementById("text1").value;
            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'test.php', true);
            xhr.responseType = 'text';
            xhr.onload = function (e) {
                if (this.status == 200) {
                    document.getElementById("result").innerHTML = this.response;
                }
            };
            xhr.send(txt);
        }
    </script>
    <form>
        <input type="text" id="text1"><br />
        <input type="button" value="发送数据" onclick="sendText()">
    </form>
    <output id="result"></output>

    后台页面

    <?php
        $str = file_get_contents('php://input');
        echo '服务器端接收数据:'.$str;
        flush();
    ?>

    演示效果如图所示:

更多...

加载中...