封装异步请求
1、将函数作为参数进行使用
2、因为获取数据是在一个注册事件中获取的,所以只有事件触发的时候才会调用此函数
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <button>发送请求1</button> <button>发送请求2</button> <script> var btn1 = document.getElementsByTagName("button")[0]; var btn2 = document.getElementsByTagName("button")[1]; btn1.onclick = function () { ajax_tool('05.php', '', 'get', function (msg) { alert(msg); }) } btn2.onclick = function () { ajax_tool_pro({ url: '05.php', data: '', method: 'get', success: function (data) { console.log(data); } }); } /* 参数1:url 参数2:数据 参数3:请求的方法 参数4:数据成功获取以后 调用的方法 */ function ajax_tool(url, data, method, success) { var ajax = new XMLHttpRequest(); if (method == 'get') { if (data) { url += '?'; url += data; } ajax.open(method, url); ajax.send(); } else { ajax.open(method, url); ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); if (data) { ajax.send(data); } else { ajax.send(); } } ajax.onreadystatechange = function () { if (ajax.readyState == 4 && ajax.status == 200) { success(ajax.responseText); } } } // url:请求的url // data:发送的数据 // method:请求的方法 // success:请求成功以后 调用的函数 function ajax_tool_pro(option) { var ajax = new XMLHttpRequest(); if (option.method == 'get') { if (option.data) { option.url += '?'; option.url += option.data; } ajax.open(option.method, option.url); ajax.send(); } else { ajax.open(option.method, option.url); ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); if (option.data) { ajax.send(option.data); } else { ajax.send(); } } ajax.onreadystatechange = function () { if (ajax.readyState == 4 && ajax.status == 200) { option.success(ajax.responseText); } } } </script> </body> </html>
<?php header("content-type:text/html;charset=utf-8"); echo '服务器已经收到请求'; ?>