307 Ajax請求參數格式:json, x-www-form-urlencoded



補充:
(1)get請求的請求參數,以查詢字符串的方式拼接在url后面;
(2)傳統的表單提交,表單數據以查詢字符串的方式傳遞給send()方法。

05.向服務器端傳遞JSON格式的請求參數.html

<!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)請求地址
        xhr.open('post', 'http://localhost:3000/json');
        // 通過請求頭告訴服務器端客戶端向服務器端傳遞的請求參數的格式是什么
        xhr.setRequestHeader('Content-Type', 'application/json');
        // JSON.stringify() 將json對象轉換為json字符串
        // 3.發送請求
        xhr.send(JSON.stringify({
            name: 'lisi',
            age: 50
        }));
        // 4.獲取服務器端響應到客戶端的數據
        xhr.onload = function() {
            console.log(xhr.responseText) // {"name":"lisi","age":50}
            console.log(typeof xhr.responseText) // string,responseText就是文本字符串
        }
    </script>
</body>

</html>

因為請求路徑是json,所以在network里,看的時候,也是看name為json的。



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM