Ajax基础(中)

2023-02-12,

这节主要在上节的基础上学会如何使用Ajax

源码下载:

链接:https://pan.baidu.com/s/1kG-vACFxneAZqONdo97XrQ

提取码:k21y

在WebStorm中打开整个工程,首先需要关注的是bin、routes、views文件夹下的内容。

在上一节介绍过如何启动web服务器,这里再介绍一种服务器的方法:选中AjaxServer-->bin-->www(服务器完成后这部分代码会自动生成),

右击,选择Run 'www',同样也可以启动服务器,这样输入网址就可以访问服务器资源了。

为什么输入localhost:3000就会返回一个页面呢?

构建服务器的时候,会生成一个routes和views文件夹,在输入网址的时候,首先会访问这两文件夹里面的内容。

routes--->index.js    index title就是index.ejs中的title,如果Express修改为其他的,返回的页面内容也会有相应的变化

var express = require('express');
var router = express.Router(); /* GET home page. 页面路由*/
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
}); module.exports = router;

views-->index.ejs

<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
</body>
</html>

我把Express--->Ajax学习大本营,返回的页面也变化了

上面能够返回页面的叫做页面路由,那么怎么返回数据呢?返回数据的叫做接口路由,这里接口路由返回一json数据。

var express = require('express');
var router = express.Router(); /* GET home page. 页面路由:是返回页面的*/
router.get('/', function(req, res, next) {
res.render('index', { title: 'Ajax学习大本营' }); }); /*接口路由:返回数据*/
router.get('/api/one',function (req,res,next){
res.json({
"state":200,
data:{
"name":"zxtang",
"age":20
}
});
});
module.exports = router;

同样的,使用Postman来测试

接下来修改一下页面路由,页面上是一个button

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button id="send">发起get请求</button>
<script>
window.addEventListener('load',function (){
var btn=document.getElementById('send');
btn.addEventListener('click',function (){
alert('点击我')
})
});
</script>
</body>
</html>

 如何使用Ajax?

在前面的基础上,我们已经知道了Ajax的一些基础,客户端发送请求是通过js来发送的,为了在客户端和服务器之间交换一些数据,我们需要在js中创建一个对象,这就要创建XMLHttpRequest对象。

所有现代浏览器均支持 XMLHttpRequest 对象,XMLHttpRequest 用于在客户端与服务器交换数据,通过该对象可以在不重新加载整个网页的情况下,对网页的某部分进行更新,使用的步骤如下:

1)创建XMLHttpRequest对象

var xhr = new XMLHttpRequest();

2)准备发送

xhr.open('get', './01check.js?username='+uname+'&password='+pw,true);

3)执行发送动作

xhr.send()
xhr.seng(String)主要用于POST方法

4)指定回调函数

onreadystatechange 事件:当请求被发送到服务器时,我们需要执行一些基于响应的任务,每当 readyState 改变时,就会触发 onreadystatechange 事件

案例1:通过XMLHttpRequest来发起请求

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button id="send">发起get请求</button>
<script>
window.addEventListener('load',function (){
var btn=document.getElementById('send');
btn.addEventListener('click',function (){
//1.创建一个XMLHttpRequest对象
var xhr = new XMLHttpRequest();
//2.准备发送
xhr.open('get','http://localhost:3000/api/one',true);
//3.发送请求
xhr.send();
//4.监听服务器的响应
xhr.addEventListener('readystatechange',function (){
//响应完成,但不一定正确
if(xhr.readyState===4){
console.log("响应完成");
}
if(xhr.status===200) {
console.log("响应正确");
}
})
})
});
</script>
</body>
</html>

显示数据内容  console.log(xhr.response);

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<button id="send">发起get请求</button>
<script>
window.addEventListener('load',function (){
var btn=document.getElementById('send');
btn.addEventListener('click',function (){
//1.创建一个XMLHttpRequest对象
var xhr = new XMLHttpRequest();
//2.准备发送
xhr.open('get','http://localhost:3000/api/one',true);
//3.发送请求
xhr.send();
//4.监听服务器的响应
xhr.addEventListener('readystatechange',function (){
//响应完成,但不一定正确
if(xhr.readyState===4){
console.log("响应完成");
}
if(xhr.status===200) {
console.log("响应正确");
//数据内容
console.log(xhr.response);
} })
})
});
</script>
</body>
</html>

案例2:在客户端浏览器附加上输入账号和密码,然后通过按钮将账号和密码数据发送给服务器,服务器接收之后,将数据封装成一个json返回 给客户端。

参照:xhr.open('get', './01check.js?username='+uname+'&password='+pw,true);

www代码:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<label>
<input id="account" type="text" name="account"><input>
</label>
<label>
<input id="pwd" type="text" name="pwd"><input>
</label>
<button id="send">发起get请求</button>
<script>
window.addEventListener('load',function (){
var btn=document.getElementById('send');
btn.addEventListener('click',function (){
//1.创建一个XMLHttpRequest对象
var xhr = new XMLHttpRequest();
var account=document.getElementById('account').value;
var pwd=document.getElementById('pwd').value;
xhr.open('get','http://localhost:3000/api/two?account='+account+'&pwd='+pwd,true)
xhr.send();
xhr.addEventListener('readystatechange',function (){
if(xhr.readyState === 4 && xhr.status === 200){
console.log(xhr.responseText);
}
})
})
});
</script>
</body>
</html>

index.js代码:

var express = require('express');
var router = express.Router();/*接口路由:返回数据*/
router.get('/api/two',function (req,res,next){
console.log(req.query);
//返回json数据
res.json({
"state":200,
data: req.query
});
});
module.exports = router;

req.query表示返回客户端发给服务器的数据,即拼接的account和pwd内容

index.ejs代码

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<label>
<input id="account" type="text" name="account"><input>
</label>
<label>
<input id="pwd" type="text" name="pwd"><input>
</label>
<button id="send">发起get请求</button>
<script>
window.addEventListener('load',function (){
var btn=document.getElementById('send');
btn.addEventListener('click',function (){
//1.创建一个XMLHttpRequest对象
var xhr = new XMLHttpRequest();
var account=document.getElementById('account').value;
var pwd=document.getElementById('pwd').value;
xhr.open('get','http://localhost:3000/api/two?account='+account+'&pwd='+pwd,true)
xhr.send();
xhr.addEventListener('readystatechange',function (){
if(xhr.readyState === 4 && xhr.status === 200){
console.log(xhr.responseText);
}
})
})
});
</script>
</body>
</html>

案例2:在客户端浏览器label表单输入账号和密码,然后通过按钮将账号和密码数据发送给服务器,服务器接收之后,将数据封装成一个json返回 给客户端。

index.js代码

var express = require('express');
var router = express.Router(); /* GET home page. 页面路由:是返回页面的*/
router.get('/', function(req, res, next) {
res.render('index', { title: 'Ajax学习大本营' }); }); /*接口路由:返回数据*/
router.get('/api/two',function (req,res,next){
console.log(req.query);
//返回一json数据给客户端,使用req.query可以获取浏览器中的拼接数据
res.json({
"state":200,
data: req.query
});
});
module.exports = router;

index.ejs代码

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<label>
<input id="account" type="text" name="account">
</label>
<label><input id="pwd" type="text" name="pwd">
</label>
<button id="send">发起get请求</button>
<script>
window.addEventListener('load',function (){
var btn=document.getElementById('send');
btn.addEventListener('click',function (){
//1.创建一个XMLHttpRequest对象
var xhr = new XMLHttpRequest();
var account=document.getElementById('account').value;
var pwd=document.getElementById('pwd').value;
xhr.open('get','http://localhost:3000/api/two?account='+account+'&pwd='+pwd,true)
xhr.send();
xhr.addEventListener('readystatechange',function (){
if(xhr.readyState === 4 && xhr.status === 200){
console.log(xhr.responseText);
}
})
})
});
</script>
</body>
</html>

首先在浏览器中输入localhost:3000返回页面,然后在label中输入账户和密码,通过button发送账户和密码给服务器,服务器将数据返回给客户端。

304表示从缓存读取数据

 

GET请求方法封装

在public文件夹下新建一个js文件,再添加AjaxTool.js

(function (window){
function AjaxTool(){
}
AjaxTool.ajaxRequest=function (url,paramObj,successCallback, failedCallback){
var xhr=new XMLHttpRequest();
xhr.open('get', url + '?' + getStrWithObject(paramObj), true);
xhr.send();
xhr.addEventListener('readystatechange', function (ev2) {
if(xhr.readyState === 4){
if(xhr.status === 200){
// 请求成功
successCallback && successCallback(xhr);
}else {
// 请求失败
failedCallback && failedCallback(xhr);
}
}
});
}; /*
{
name: "张三",
age: 18
}
[‘name="张三"’, “age=18”, "random=323323232"]
name="张三"&age=18
*/
/**
* 把对象转换成字符串
*/
function getStrWithObject(paramObj) {
var resArr=[];
//1.转换对象
for(var key in paramObj)
{
var str = key + '=' + paramObj[key];
resArr.push(str);
}
//2.拼接时间戳
resArr.push('random='+getRandomStr());
//3.数组转成字符串
return resArr.join('&');
}
/**
* 获取随机时间戳
* @returns {number}
*/
function getRandomStr() {
return Math.random() + (new Date().getTime());
}
window.AjaxTool = AjaxTool;
})(window)

index.js添加以下:

router.get('/api/three', function(req, res, next) {
res.json({
"state": 200,
"data": req.query
});
});

index.ejs代码:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<label>
<input id="account" type="text" name="account">
</label>
<label><input id="pwd" type="text" name="pwd">
</label>
<button id="send">发起get请求</button>
<script src="/js/AjaxTool.js"></script>
<script>
window.addEventListener('load',function (){
var btn=document.getElementById('send');
btn.addEventListener('click',function (){
//1.创建一个XMLHttpRequest对象
var xhr = new XMLHttpRequest();
var account=document.getElementById('account').value;
var pwd=document.getElementById('pwd').value;
// 2. 参数对象
var paramsObj = {
"account": account,
"pwd": pwd
}
AjaxTool.ajaxRequest('http://localhost:3000/api/three', paramsObj, function (xhr) {
// 处理成功的回调
console.log('请求成功:', xhr.responseText);
}, function (xhr) {
// 处理失败的回调
console.log('请求失败');
})
})
});
</script>
</body>
</html>

那如果要测试请求失败,怎么?

AjaxToolOne.js

(function (window){
function AjaxTool(){
}
AjaxTool.ajaxRequest=function (url,paramObj,timeOut,successCallback, failedCallback){
var xhr=new XMLHttpRequest();
xhr.open('get', url + '?' + getStrWithObject(paramObj), true);
xhr.send();
xhr.addEventListener('readystatechange', function (ev2) {
if(xhr.readyState === 4){
if(xhr.status === 200){
// 请求成功
successCallback && successCallback(xhr);
clearTimeout(timer);//清除定时器
}else {
// 请求失败
failedCallback && failedCallback(xhr);
}
}
});
// timeOut0 代表不限制请求的时间
//如果时间超过timeOut,那么返回一个加载超时
var timer = null;
if(timeOut > 0){
//创建定时器
timer = setTimeout(function () {
// 取消请求
xhr.abort();
}, timeOut);
}
}; /*
{
name: "张三",
age: 18
}
[‘name="张三"’, “age=18”, "random=323323232"]
name="张三"&age=18
*/
/**
* 把对象转换成字符串
*/
function getStrWithObject(paramObj) {
var resArr=[];
//1.转换对象
for(var key in paramObj)
{
var str = key + '=' + paramObj[key];
resArr.push(str);
}
//2.拼接时间戳
resArr.push('random='+getRandomStr());
//3.数组转成字符串
return resArr.join('&');
}
/**
* 获取随机时间戳
* @returns {number}
*/
function getRandomStr() {
return Math.random() + (new Date().getTime());
}
window.AjaxTool = AjaxTool;
})(window)

index,.js

router.get('/api/four', function(req, res, next) {
//给服务器设置延时,测试请求延时
setTimeout(function () {
res.json({
"state": 200,
"data": "测试请求延时"
});
}, 2000);
});

index.ejs

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<label>
<input id="account" type="text" name="account">
</label>
<label><input id="pwd" type="text" name="pwd">
</label>
<button id="send">发起get请求</button>
<script src="/js/AjaxToolOne.js"></script>
<script>
window.addEventListener('load',function (){
var btn=document.getElementById('send');
btn.addEventListener('click',function (){
//1.创建一个XMLHttpRequest对象
var xhr = new XMLHttpRequest();
var account=document.getElementById('account').value;
var pwd=document.getElementById('pwd').value;
// 2. 参数对象
var paramsObj = {
"account": account,
"pwd": pwd
}
AjaxTool.ajaxRequest('http://localhost:3000/api/four', paramsObj,2000, function (xhr) {
// 处理成功的回调
console.log('请求成功:', xhr.responseText);
}, function (xhr) {
// 处理失败的回调
console.log('请求失败');
})
})
});
</script>
</body>
</html>

POST请求方法

index.js添加POST请求路由:

router.post('/api/five', function(req, res, next) {
console.log(req.body);
res.json({
"state": 200,
"data": "你发起的是一个post请求"
});
});

和GET请求不同,POST请求需要设置一个请求头,index.ejs:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
<style>
body {
background-color: skyblue;
}
</style>
</head>
<body>
<label>
<input id="account" type="text" name="account">
</label>
<label>
<input id="pwd" type="text" name="pwd">
</label>
<button id="send">发起Post请求</button>
<script>
window.addEventListener('load', function (ev) {
var btn = document.getElementById('send');
btn.addEventListener('click', function (ev1) { // 1. 获取用户输入的内容
var account = document.getElementById('account').value;
var pwd = document.getElementById('pwd').value; // 2. 创建网络请求对象
var xhr = new XMLHttpRequest();
xhr.open('post', 'http://localhost:3000/api/five', true);
// 设置请求头
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send('name=zs&age=19');
xhr.addEventListener('readystatechange', function (ev2) {
if(xhr.readyState === 4 ){
if(xhr.status === 200){
console.log(xhr.responseText);
}else {
console.log('请求失败!');
}
}
});
});
});
</script>
</body>
</html>
req.body表示服务器接收到客户端发送过来的数据

Ajax基础(中)的相关教程结束。

《Ajax基础(中).doc》

下载本文的Word格式文档,以方便收藏与打印。