(function () { var ajax = { getxhr: function () { return new XMLHttpRequest(); }, get: function (url, fun, sync = true) { // 调用对象中的方法获取xhr对象 var xhr = this.getxhr(); // 设置状态码改变事件 xhr.onreadystatechange = function () { // 状态码为4 说明服务器返回结束 客户端接收到全部数据 if (xhr.readyState == 4) { fun(xhr.responseText); } } xhr.open('get', url, sync); xhr.send(); }, post: function (url, post_data, sync = true, fun) { var xhr = this.getxhr(); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { fun(xhr.responseText); } } xhr.open('post', url, sync); xhr.send(post_data); } } // 封装时将封装内容给window对象 // 不要和现有window对象中的属性重名 window.myajax = ajax; })()
封装完成后使用时直接在需要使用的位置引入 例如: <script src="./ajax.js"></script>
通过myajax.get ( ) / post ( )的方式使用
例:html部分
<!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>
<input type="button" value="按钮">
</body>
<script src="./ajax.js"></script>
<script>document.getElementsByTagName('input')[0].onclick = function () {
myajax.get('http://127.0.0.1/gets', function (d) {
alert(d);
})
}
</script>
</html>
服务器部分:
var http = require('http'); var fs = require('fs'); var url = require('url'); var server = http.createServer(); server.listen(8080,function(){ console.log('8080') }); server.on('request',function(req,res){ var urls = url.parse(req.url,true); if (urls.pathname == '/gets'){ res.end('hello world!'); }else{ fs.readFile('.'+urls.pathname,function(err,data_str){ if(!err){ res.end(data_str); }else{ res.end(''); } }) } })
这里使用匿名函数自调用的方法是为了避免与引入的其他文件(如jQuery)重名