知识点
-
创建一个请求
var xhr = new XMLHttpRequest();
-
准备发送
xhr.open('get','http://localhost:3000/api/one',true);
-
执行发送动作
xhr.send(null);
-
监听服务器响应
xhr.addEventListener('readystatechange',function (ev2) { // console.log(xhr.readyState); if (xhr.readyState === 4){ // 意味着服务器响应结束 // 不代表服务器响应一定正确 // console.log(xhr.status); if (xhr.status === 200){ console.log(xhr.response); } } })
-
xhr.readyState === 4意味着响应结束,但不一定响应正确。
-
xhr.status 状态码
-
xhr.response 响应结果
过程
-
配置好服务器后,启动服务器
-
在index.js中,写好接口路由和页面路由
var express = require('express'); var router = express.Router(); /* GET home page. */ /* 页面路由 */ router.get('/', function(req, res, next) { res.render('index', { title: '测试中心' }); }); /* 接口路由 */ router.get('/api/one', function(req, res, next) { res.json({ "start":200, "data":{ "name":"郇凯", "intro":"I like zheng" } }) }); module.exports = router;
-
在index.ejs中写请求访问
<!DOCTYPE html> <html lang="ch"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="id=edge"> <title></title> </head> <body> <button id="send">发起get请求</button> <script> window.addEventListener('load',function (ev) { var btn = document.getElementById('send'); btn.addEventListener('click',function (ev1) { // 1. 创建一个请求对象 var xhr = new XMLHttpRequest(); // 2. 准备发送 xhr.open('get','http://localhost:3000/api/one',true); // 3. 执行发送动作 xhr.send(null); // 4. 监听服务器响应 xhr.addEventListener('readystatechange',function (ev2) { // console.log(xhr.readyState); if (xhr.readyState === 4){ // 意味着服务器响应结束 // 不代表服务器响应一定正确 // console.log(xhr.status); if (xhr.status === 200){ console.log(xhr.response); } } }) }); }) </script> </body> </html>