javascript - 练习题:AJAX请求,node.js响应

时间:2022-11-22 07:57:58

AJAX部分

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ajax</title>
</head>

<body>
用户:<input id="user" type="text"><br>
密码:<input id="pass" type="text"><br>
<button value="登录" id="btn">登录</button>
<script>
var btn = document.querySelector('button');
var user = document.querySelector('input#user');
var pass = document.querySelector('input#pass');

// 封装AJAX的get请求;
function ajax(option) {
var ajax = new XMLHttpRequest();
ajax.open(option.type, option.url + '?' + JsonToString(option.data), true); // 异步
ajax.send();
ajax.onreadystatechange = function () {
if (ajax.readyState == 4) {
if (ajax.status >= 200 && ajax.status < 300 || ajax.status == 304) {
option.success(ajax.responseText);
} else {
console.log('服务器错误');
}
}
}
}
// 封装josn to String
// {user:'anderson',pass:'123456'} => user=anderson&pass=123456
function JsonToString(json) {
var arr = [];
for (var i in json) {
arr.push(i + '=' + json[i]);
}
return arr.join('&'); // user=anderson&pass=123456
}

// 事件绑定到 button 上
btn.onclick = function () {
ajax({
type: 'get',
url: 'http://localhost:9217',
data: {
user: user.value,
pass: pass.value,
},
success: function (data) {
console.log(data);
if(data == '登录成功'){
document.body.style.background = 'gray';
}else{
console.log('登录失败');
}
},
error: function () {
console.log('服务器错误');
}
});
}

</script>
</body>

</html>

node.js 部分

// node.js 环境下的 web 服务,相当于:http://localhost:9217
var http = require('http');
http.createServer(function (request, response) {
response.setHeader('Access-Control-Allow-Origin', '*');
var url = request.url.substring(2); // 获取传来的参数
console.log(url);
var arr = url.split('&'); // 字符串转换成对象
var json = {}; // 形如: {user:anderson,pass:123456}
for (var i = 0; i < arr.length; i++) {
json[arr[i].split('=')[0]] = arr[i].split('=')[1];
}
// console.log(json['user']);
if (json['user'] == 'anderson' && json['pass'] == '123456') { // 基本判断
response.write('登录成功') // 可以回传
}else{
console.log("登录失败"); // 服务端输出
}
response.end();
}).listen(9217);