原生js 完整封装ajax
最近开始看了看跟Node相关的内容,联想到了前后台的交互,于是记录一下自己封装的ajax,初学者,写的糙,望见谅~~
function ajax(json){ if(window.XMLHttpRequest){ var ajax = new XMLHttpRequest(); } else{ var ajax = new ActiveXObject( "Microsoft.XMLHTTP" ); } if(json.type=='get'){ ajax.open('get',json.url+'?'+JsonToString(json.data),true); ajax.send(); } else if(json.type=='post'){ ajax.open('post',json.url,true); ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); ajax.send(JsonToString(json.data)); } ajax.onreadystatechange = function(){ if(ajax.readyState == 4){ if(ajax.status>=200 && ajax.status<300 || ajax.status == 304){ json.success(ajax.responseText); } else{ json.error && json.error(); } }; }; function JsonToString(json){ var arr = []; for(var i in json){ arr.push(i+'='+json[i]); }; return arr.join('&'); } }
验证
btn.onclick = function(){ ajax({ 'url':'http://localhost:9102', 'type':'get', 'data':{ user:user.value, pass:pass.value }, success:function(data){ console.log(data) } }) } btn.onclick = function(){ ajax({ 'url':'http://localhost:9102', 'type':'post', 'data':{ user:user.value, pass:pass.value }, success:function(data){ console.log(data) } }) }
后台内容
var http = require('http'); urlLib = require('url'), var querystring = require('querystring'); http.createServer(function(req,res){ res.setHeader('Access-Control-Allow-Origin','*');//允许跨域 //get var json = urlLib.parse(req.url,true).query; //post var str = ''; req.on('data',function(data){ str += data; }); req.on('end',function(){ var json = querystring.parse(str); res.end(); }); }).listen(9102);
相关推荐
lyqdanang 2020-08-16
坚持着执着 2020-06-16
TONIYH 2020-06-05
kentrl 2020-11-10
结束数据方法的参数,该如何定义?-- 集合为自定义实体类中的结合属性,有几个实体类,改变下标就行了。<input id="add" type="button" value="新增visitor&quo
ajaxyan 2020-11-09
zndy0 2020-11-03
学留痕 2020-09-20
Richardxx 2020-11-09
learningever 2020-09-19
chongxiaocheng 2020-08-16
ajaxhe 2020-08-16
curiousL 2020-08-03
TONIYH 2020-07-22
时光如瑾雨微凉 2020-07-19
83510998 2020-07-18
坚持着执着 2020-07-16
jiaguoquan00 2020-07-07