
可復(fù)制的代碼
<!DOCTYPE html>
<html lang="en">
<head>
? <meta charset="UTF-8">
? <meta name="viewport" content="width=device-width, initial-scale=1.0">
? <meta http-equiv="X-UA-Compatible" content="ie=edge">
? <title>Document</title>
</head>
<body>
? <script>
? ? function ajax_method(url, data, method, success) {
? ? ? // 異步對(duì)象
? ? ? var ajax = new XMLHttpRequest();
? ? ? // get 跟post? 需要分別寫不同的代碼
? ? ? if (method == 'get') {
? ? ? ? // get請求
? ? ? ? if (data) {
? ? ? ? ? // 如果有值
? ? ? ? ? url += '?';
? ? ? ? ? url += data;
? ? ? ? } else {
? ? ? ? }
? ? ? ? // 設(shè)置 方法 以及 url
? ? ? ? ajax.open(method, url);
? ? ? ? // send即可
? ? ? ? ajax.send();
? ? ? } else {
? ? ? ? // post請求
? ? ? ? // post請求 url 是不需要改變
? ? ? ? ajax.open(method, url);
? ? ? ? // 需要設(shè)置請求報(bào)文
? ? ? ? ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
? ? ? ? // 判斷data send發(fā)送數(shù)據(jù)
? ? ? ? if (data) {
? ? ? ? ? // 如果有值 從send發(fā)送
? ? ? ? ? ajax.send(data);
? ? ? ? } else {
? ? ? ? ? // 木有值 直接發(fā)送即可
? ? ? ? ? ajax.send();
? ? ? ? }
? ? ? }
? ? ? // 注冊事件
? ? ? ajax.onreadystatechange = function () {
? ? ? ? // 在事件中 獲取數(shù)據(jù) 并修改界面顯示
? ? ? ? if (ajax.readyState == 4 && ajax.status == 200) {
? ? ? ? ? // console.log(ajax.responseText);
? ? ? ? ? // 將 數(shù)據(jù) 讓 外面可以使用
? ? ? ? ? // return ajax.responseText;
? ? ? ? ? // 當(dāng) onreadystatechange 調(diào)用時(shí) 說明 數(shù)據(jù)回來了
? ? ? ? ? // ajax.responseText;
? ? ? ? ? // 如果說 外面可以傳入一個(gè) function 作為參數(shù) success
? ? ? ? ? success(ajax.responseText);
? ? ? ? }
? ? ? }
? ? }
? </script>
</body>
</html>