准备自己封装一个原生ajax,什么都没想直接开干,写完后缺陷很多,不堪入目。
最后上百度,受这篇博文启发https://www.cnblogs.com/chenzechuang/p/6660328.html,可以模仿jQuery ajax的格式来进行封装
首先看一下调用时的样子
var params = { word1: 'deep', word2: 'dark', word3: 'develop' } ajax({ method: 'post', url: 'http://127.0.0.1:8081/post_test', data: params, async: true, success: function (data) { console.log(data) }, error: function (err) { console.log(err) } })
总之就是将所有参数存入一个对象中以对象形式传入ajax方法
ajax函数的详细代码:
function ajax(obj) { //设置async默认为true if(obj.async==null){ obj.async = true; } //callback函数利用闭包访问obj和xhr对象 function callback() { if (xhr.status == 200) { obj.success(xhr.responseText) } else { obj.error("error" + xhr.status) } } var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { callback();//利用闭包调用callback } }; if (obj.data != null) { var uri = '?'; for (let i in obj.data) { uri += i + "=" + obj.data[i] + "&"; } uri = uri.substring(0, uri.length - 1); } else { var uri = ''; } //get请求 if (obj.method == 'get') { xhr.open("get", obj.url + uri, obj.async); xhr.send(); } //post请求 else if (obj.method == 'post') { uri = uri.substring(1,uri.length); xhr.open(obj.method, obj.url, obj.async); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.send(uri); } }
后端用node写的代码(可无视掉):
var express = require('express'); var app = express(); var bodyParser = require('body-parser'); var urlencodedParser = bodyParser.urlencoded({extended:false}) //设置跨域访问 app.all('*', function(req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS"); res.header("X-Powered-By",' 3.2.1') res.header("Content-Type", "application/json;charset=utf-8"); next(); }); app.get('/get_test',function(req,res){ var response = { word1: req.query.word1, word2: req.query.word2, word3: req.query.word3 } res.send(response) }) app.post('/post_test',urlencodedParser,function(req,res){ var response = { word1: req.body.word1, word2: req.body.word2, word3: req.body.word3 } res.send(response) }) app.listen(8081)
调用ajax后在浏览器输出的结果: