前两天闲着没事爬了下校园网的信息,实现了模拟登陆然后获取课表,考勤表,空教室的信息等,想着顺便结合前端也都实现一下。以前在请求接口数据时基本都利用了jquery ajax,方便嘛,这次我将原生拿出来溜溜,还是要知道原理的好。
先来说说什么是ajax
ajax是一种创建交互式网页应用的技术,通过在后台与服务器进行少量数据交换使网页异步更新。
ajax请求步骤
1.创建ajax的核心对象XMLHttpRequest
if (
window.XMLHttpRequest) {
xmlhttp =
new XMLHttpRequest();
//兼容IE7+,firefox,chrome,opera,safari
}
else if (
window.ActiveXObject) {
xmlhttp =
new ActiveXObject(
"Microsoft.XMLHTTP");
}
else {
xmlhttp =
null;
return;
}
2.向服务器发送请求
其中涉及到了两个方法open和send
xmlhttp.open(method,url,async)参数分别表示请求方法,请求路径,请求方式(异步/同步)
xmlhttp.send()这里表示发送数据
需要注意的是这里get和post的区别
在get请求中参数被携带在请求url的后边,这里的send方法传入参数为空。
在post请求中需要将参数变换为这类的字符串username=111&password=222
function formatParams(data) {
var arr = [];
for(
var name
in data){
arr.push(name +
'=' + data[name]);
}
return arr.join(
"&");
}
然后这是请求头
xmlhttp
.setRequestHeader(
"Content-type",
"application/x-www-form-urlencoded")
3.服务器处理
responseText 获得字符串形式的响应数据
responseXML 获得XML形式的响应数据
同步处理:例如
xmlhttp.open(
"GET",
...,false);
xmlhttp.send();
console.log(xmlhttp.responseText);
异步处理:例如
xmlhttp
.onreadystatechange = function(){
if (xmlhttp
.readyState ==
4 && xmlhttp
.status ==
200) {
console
.log(xmlhttp
.responseText)
}
}
其中readyState表示请求步骤,status表示状态码
状态步骤0请求未初始化1服务器建立连接2请求已接受3请求处理中4请求已完成
现在来配合后端说下哈哈
function baseAjax() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp =
new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlhttp =
new ActiveXObject(
"Microsoft.XMLHTTP");
}
else {
xmlhttp =
null;
return;
}
xmlhttp.open(
arguments[
0],
arguments[
1],
true);
var callback =
arguments[
3];
xmlhttp.onreadystatechange =
function(){
if (xmlhttp.readyState ==
4 && xmlhttp.status ==
200) {
callback(
JSON.parse(xmlhttp.responseText));
}
}
if (
arguments[
0] ==
'GET') {
xmlhttp.send();
}
else {
var str = formatParams(
arguments[
2]);
console.log(str);
xmlhttp.setRequestHeader(
"Content-type",
"application/x-www-form-urlencoded");
xmlhttp.send(str);
}
}
var model = {};
baseAjax(
'GET',
'http://localhost:4000/vercode',model,
function(data){
console.log(data);
});
var model = {
username : ,
password :
};
baseAjax(
'POST',
'http://localhost:4000/login',model,
function(data){
console.log(data);
});
后端使用的是node+express,接受参数这样来处理req.body.username
顺便来提一下node接受参数的形式
请求路径获取参数方法…?username=111&password=222req.query.username…/:username/:passwordreq.params.usernamepost请求req.body.username(借助body-parser)