305 Ajax服务器端响应的数据格式


<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>

<body>
    <script type="text/javascript">
        // 1.创建ajax对象
        var xhr = new XMLHttpRequest();
        // 2.告诉Ajax对象要向哪发送请求,以什么方式发送请求
        // 1)请求方式 2)请求地址
        // 访问到的时候,不是访问http://localhost:3000/responseData,而是访问 http://localhost:3000/02.处理服务器端返回的JSON数据.html,这样就是完整执行这个文件的代码,否则只执行这个文件的部分代码。如果是访问http://localhost:3000/responseData,则返回后台指定的数据{ "name": "zs" }。
        xhr.open('get', 'http://localhost:3000/responseData');
        // 3.发送请求
        xhr.send();
        // 4.获取服务器端响应到客户端的数据
        xhr.onload = function() {
            console.log(xhr.responseText); // responseText就是文本字符串,json字符串{"name":"zs"}
            console.log(typeof xhr.responseText); // string
            // 将JSON字符串转换为JSON对象
            var responseText = JSON.parse(xhr.responseText);
            // 测试:在控制台输出处理结果
            console.log(responseText) // {name: "zs"}
            console.log(responseText instanceof Object); // true

            // 将数据和html字符串进行拼接
            var str = '<h2>' + responseText.name + '</h2>';
            // 将拼接的结果追加到页面中
            document.body.innerHTML = str;
        }
    </script>
</body>

</html>
原文地址:https://www.cnblogs.com/jianjie/p/12341541.html