1. 程式人生 > 其它 >jq 和ajax

jq 和ajax

技術標籤:jq和ajax

jq 和ajax


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
        // ajax函式封裝
// method請求方式,可以是get / post // url 請求路徑 // param 請求引數 // callback 回撥函式 function ajax(method, url, param, callback) { const xhr = new XMLHttpRequest(); // 請求的方式判斷 if (method === 'get') { xhr.open('get', `${url}?${param}
`
) } else { xhr.open('post', url); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); } xhr.onload = function() { const jRes = JSON.parse(xhr.responseText); callback(jRes); }
if (method === 'get') { xhr.send(); } else { xhr.send(param) } } // 傳送get請求測試 ajax('get', 'http://127.0.0.1:3001/validate', 'userName=tom', function(res) { console.log(res) }) // 傳送 post請求測試 ajax('post', 'http://127.0.0.1:3001/toHuoxing', 'content=葬愛家族表示頭禿', function(res) { console.log(res) }) </script> </head> <body> </body> </html>

1 先判斷get 和 post請求 , 傳送url , get請求param在url裡進行拼接 , post要在open後傳送請求頭 , 讓瀏覽器知道是post請求

2 在onload裡 , 將接收資料轉換json資料 ,利用callback回撥函式傳出

3 判斷請求型別 get就直接send傳送 post的話 send中傳送param引數