32·灵魂前端工程师养成-[前后分离]AJAX原理及JSON详解

2022-10-31 18:09:33 浏览数 (1)

  • 下载server.js

  • 编写客户端代码
  • 使用AJAX加载CSS
  • 使用AJAX加载js
  • 使用AJAX加载HTML
  • 触发错误事件
  • 使用AJAX加载XML
  • 加载JSON
  • 综合应用-加载分页
  • 完整代码

-曾老湿, 江湖人称曾老大。 -笔者QQ:133411023、253097001 -笔者交流群:198571640 -笔者微信:z133411023


-多年互联网运维工作经验,曾负责过大规模集群架构自动化运维管理工作。 -擅长Web集群架构与自动化运维,曾负责国内某大型金融公司运维工作。 -devops项目经理兼DBA。 -开发过一套自动化运维平台(功能如下): 1)整合了各个公有云API,自主创建云主机。 2)ELK自动化收集日志功能。 3)Saltstack自动化运维统一配置管理工具。 4)Git、Jenkins自动化代码上线及自动化测试平台。 5)堡垒机,连接Linux、Windows平台及日志审计。 6)SQL执行及审批流程。 7)慢查询日志分析web界面。


下载server.js


AJAX介绍

AJAX:Async JavaScript And XML

异步 JS 和 XML ... 什么玩意

说白了,就是用JS发请求和收响应。

AJAX是浏览器上的功能: 1.浏览器可以发请求,收响应 2.浏览器在window上加了一个XMLHttpRequest函数 3.用这个构造函数(类)可以构造出一个对象 4.JS通过它实现发请求,收响应。

之前课程中,我们在学习HTTP写过一个server.js的代码:

代码语言:javascript复制
var http = require('http')
var fs = require('fs')
var url = require('url')
var port = process.argv[2]

if(!port){
  console.log('请指定端口号好不啦?nnode server.js 8888 这样不会吗?')
  process.exit(1)
}

var server = http.createServer(function(request, response){
  var parsedUrl = url.parse(request.url, true)
  var pathWithQuery = request.url 
  var queryString = ''
  if(pathWithQuery.indexOf('?') >= 0){ queryString = pathWithQuery.substring(pathWithQuery.indexOf('?')) }
  var path = parsedUrl.pathname
  var query = parsedUrl.query
  var method = request.method

  /******** 从这里开始看,上面不要看 ************/

  console.log('有个傻子发请求过来啦!路径(带查询参数)为:'   pathWithQuery)

  if(path === '/'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    var accept = request.headers["accept"];
    console.log("accept:");
    console.log(accept);
    response.write(`
        <!DOCTYPE html>
        <head>
            <link rel="stylesheet" href="/x">
        </head>
        <body>
            <h1>曾老湿</h1>
            <script src="/y"></script>
        </body>
    `)
    response.end()
  } else if(path === '/x'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/css;charset=utf-8')
    response.write(`body{color: red;}`)
    response.end()
  } else if(path === '/y'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
    response.write(`console.log('这是JS内容')`)
    response.end()
  } else {
    response.statusCode = 404
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(`你输入的路径不存在对应的内容`)
    response.end()
  }

  /******** 代码结束,下面不要看 ************/
})

server.listen(port)
console.log('监听 '   port   ' 成功n请用在空中转体720度然后用电饭煲打开 http://localhost:'   port)

使用VScode打开,然后创建js项目,使用node启动项目,打开浏览器访问。

如上代码,但是node这个启动命令我们在更改页面的时候,不会重新加载,还得重启服务,所以我们使用node-dev来启动,那么 首先我们需要安装一个node-dev

代码语言:javascript复制
MacBook-pro:HTML driverzeng$ npm i -g node-dev

MacBook-pro:ajax-1 driverzeng$ yarn global add node-dev

启动服务

代码语言:javascript复制
MacBook-pro:ajax-1 driverzeng$ node-dev server.js 9090

编写客户端代码

也就是说,刚才我们部署的是服务端,接下来,我们需要加上两个请求页面,光有服务,没有页面是不行的。

第一个页面,index.html

代码语言:javascript复制
var http = require('http')
var fs = require('fs')
var url = require('url')
var port = process.argv[2]

if(!port){
  console.log('请指定端口号好不啦?nnode server.js 8888 这样不会吗?')
  process.exit(1)
}

var server = http.createServer(function(request, response){
  var parsedUrl = url.parse(request.url, true)
  var pathWithQuery = request.url 
  var queryString = ''
  if(pathWithQuery.indexOf('?') >= 0){ queryString = pathWithQuery.substring(pathWithQuery.indexOf('?')) }
  var path = parsedUrl.pathname
  var query = parsedUrl.query
  var method = request.method

  /******** 从这里开始看,上面不要看 ************/

  console.log('有个傻子发请求过来啦!路径(带查询参数)为:'   pathWithQuery)

  if(path === '/index.html'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    var accept = request.headers["accept"];
    console.log("accept:");
    console.log(accept);
    response.write(`
        <!DOCTYPE html>
        <head>
            <link rel="stylesheet" href="/x">
            <title>曾老湿 AJAX 页面</title>
        </head>
        <body>
            <h1>曾老湿 AJAX 默认页面</h1>
            <script src="/y"></script>
        </body>
    `)
    response.end()
  } else if(path === '/x'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/css;charset=utf-8')
    response.write(`body{color: red;}`)
    response.end()
  } else if(path === '/y'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
    response.write(`console.log('这是JS内容')`)
    response.end()
  } else {
    response.statusCode = 404
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(`你输入的路径不存在对应的内容`)
    response.end()
  }

  /******** 代码结束,下面不要看 ************/
})

server.listen(port)
console.log('监听 '   port   ' 成功n请用在空中转体720度然后用电饭煲打开 http://localhost:'   port)

第二个页面 main.js

代码语言:javascript复制
var http = require('http')
var fs = require('fs')
var url = require('url')
var port = process.argv[2]

if(!port){
  console.log('请指定端口号好不啦?nnode server.js 8888 这样不会吗?')
  process.exit(1)
}

var server = http.createServer(function(request, response){
  var parsedUrl = url.parse(request.url, true)
  var pathWithQuery = request.url 
  var queryString = ''
  if(pathWithQuery.indexOf('?') >= 0){ queryString = pathWithQuery.substring(pathWithQuery.indexOf('?')) }
  var path = parsedUrl.pathname
  var query = parsedUrl.query
  var method = request.method

  /******** 从这里开始看,上面不要看 ************/

  console.log('有个傻子发请求过来啦!路径(带查询参数)为:'   pathWithQuery)

  if(path === '/index.html'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    var accept = request.headers["accept"];
    console.log("accept:");
    console.log(accept);
    response.write(`
        <!DOCTYPE html>
        <head>
            <link rel="stylesheet" href="/x">
            <title>曾老湿 AJAX 页面</title>
        </head>
        <body>
            <h1>曾老湿 AJAX 默认页面</h1>
            <script src="/y"></script>
        </body>
    `)
    response.end()
  } else if(path === '/main.js'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
    response.write(`console.log('我是曾老湿main.js页面')`)
    response.end()
  } else if(path === '/y'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
    response.write(`console.log('这是JS内容')`)
    response.end()
  } else {
    response.statusCode = 404
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(`你输入的路径不存在对应的内容`)
    response.end()
  }

  /******** 代码结束,下面不要看 ************/
})

server.listen(port)
console.log('监听 '   port   ' 成功n请用在空中转体720度然后用电饭煲打开 http://localhost:'   port)

然后我们把main.js和index.html结合起来。

代码语言:javascript复制
var http = require('http')
var fs = require('fs')
var url = require('url')
var port = process.argv[2]

if(!port){
  console.log('请指定端口号好不啦?nnode server.js 8888 这样不会吗?')
  process.exit(1)
}

var server = http.createServer(function(request, response){
  var parsedUrl = url.parse(request.url, true)
  var pathWithQuery = request.url 
  var queryString = ''
  if(pathWithQuery.indexOf('?') >= 0){ queryString = pathWithQuery.substring(pathWithQuery.indexOf('?')) }
  var path = parsedUrl.pathname
  var query = parsedUrl.query
  var method = request.method

  /******** 从这里开始看,上面不要看 ************/

  console.log('有个傻子发请求过来啦!路径(带查询参数)为:'   pathWithQuery)

  if(path === '/index.html'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    var accept = request.headers["accept"];
    console.log("accept:");
    console.log(accept);
    response.write(`
        <!DOCTYPE html>
        <head>
            <link rel="stylesheet" href="/x">
            <title>曾老湿 AJAX 页面</title>
        </head>
        <body>
            <h1>曾老湿 AJAX 默认页面</h1>
            <script src="/main.js"></script>
        </body>
    `)
    response.end()
  } else if(path === '/main.js'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
    response.write(`console.log('我是曾老湿main.js页面')`)
    response.end()
  } else if(path === '/y'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
    response.write(`console.log('这是JS内容')`)
    response.end()
  } else {
    response.statusCode = 404
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(`你输入的路径不存在对应的内容`)
    response.end()
  }

  /******** 代码结束,下面不要看 ************/
})

server.listen(port)
console.log('监听 '   port   ' 成功n请用在空中转体720度然后用电饭煲打开 http://localhost:'   port)

我们以前开发,都是直接写index.html 或者 style.css 或者 main.js 这次为什么直接在服务端写好了呢?修改代码成文件的方式,我们把代码中的index.html拿出来单独保存到一个文件中,然后引用

代码语言:javascript复制
<!DOCTYPE html>
<head>
    <title>曾老湿 AJAX 页面</title>
</head>
<body>
    <h1>曾老湿 AJAX 默认页面</h1>
    <script src="/main.js"></script>
</body>

代码语言:javascript复制
var http = require('http')
var fs = require('fs')
var url = require('url')
var port = process.argv[2]

if(!port){
  console.log('请指定端口号好不啦?nnode server.js 8888 这样不会吗?')
  process.exit(1)
}

var server = http.createServer(function(request, response){
  var parsedUrl = url.parse(request.url, true)
  var pathWithQuery = request.url 
  var queryString = ''
  if(pathWithQuery.indexOf('?') >= 0){ queryString = pathWithQuery.substring(pathWithQuery.indexOf('?')) }
  var path = parsedUrl.pathname
  var query = parsedUrl.query
  var method = request.method

  /******** 从这里开始看,上面不要看 ************/

  console.log('有个傻子发请求过来啦!路径(带查询参数)为:'   pathWithQuery)

  if(path === '/index.html'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    var accept = request.headers["accept"];
    console.log("accept:");
    console.log(accept);
    response.write(fs.readFileSync('public/index.html'))
    response.end()
  } else if(path === '/main.js'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
    response.write(`console.log('我是曾老湿main.js页面')`)
    response.end()
  } else if(path === '/y'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
    response.write(`console.log('这是JS内容')`)
    response.end()
  } else {
    response.statusCode = 404
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(`你输入的路径不存在对应的内容`)
    response.end()
  }

  /******** 代码结束,下面不要看 ************/
})

server.listen(port)
console.log('监听 '   port   ' 成功n请用在空中转体720度然后用电饭煲打开 http://localhost:'   port)

依然可以加载页面,那么我们把main.js做同样的事情,把它挪出来。

代码语言:javascript复制
var http = require('http')
var fs = require('fs')
var url = require('url')
var port = process.argv[2]

if(!port){
  console.log('请指定端口号好不啦?nnode server.js 8888 这样不会吗?')
  process.exit(1)
}

var server = http.createServer(function(request, response){
  var parsedUrl = url.parse(request.url, true)
  var pathWithQuery = request.url 
  var queryString = ''
  if(pathWithQuery.indexOf('?') >= 0){ queryString = pathWithQuery.substring(pathWithQuery.indexOf('?')) }
  var path = parsedUrl.pathname
  var query = parsedUrl.query
  var method = request.method

  /******** 从这里开始看,上面不要看 ************/

  console.log('有个傻子发请求过来啦!路径(带查询参数)为:'   pathWithQuery)

  if(path === '/index.html'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    var accept = request.headers["accept"];
    console.log("accept:");
    console.log(accept);
    response.write(fs.readFileSync('public/index.html'))
    response.end()
  } else if(path === '/main.js'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
    response.write(fs.readFileSync('public/main.js'))
    response.end()
  } else if(path === '/y'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
    response.write(`console.log('这是JS内容')`)
    response.end()
  } else {
    response.statusCode = 404
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(`你输入的路径不存在对应的内容`)
    response.end()
  }

  /******** 代码结束,下面不要看 ************/
})

server.listen(port)
console.log('监听 '   port   ' 成功n请用在空中转体720度然后用电饭煲打开 http://localhost:'   port)

使用AJAX加载CSS

以前我们直接用<link rel=stylesheet href="1.css">方式来加载CSS,今天我们使用AJAX的方式来加载CSS

首先,不用AJAX的方法,新建一个文件叫style.css

代码语言:javascript复制
h1{
    color: blue;
}

代码语言:javascript复制
var http = require('http')
var fs = require('fs')
var url = require('url')
var port = process.argv[2]

if(!port){
  console.log('请指定端口号好不啦?nnode server.js 8888 这样不会吗?')
  process.exit(1)
}

var server = http.createServer(function(request, response){
  var parsedUrl = url.parse(request.url, true)
  var pathWithQuery = request.url 
  var queryString = ''
  if(pathWithQuery.indexOf('?') >= 0){ queryString = pathWithQuery.substring(pathWithQuery.indexOf('?')) }
  var path = parsedUrl.pathname
  var query = parsedUrl.query
  var method = request.method

  /******** 从这里开始看,上面不要看 ************/

  console.log('有个傻子发请求过来啦!路径(带查询参数)为:'   pathWithQuery)

  if(path === '/index.html'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    var accept = request.headers["accept"];
    console.log("accept:");
    console.log(accept);
    response.write(fs.readFileSync('public/index.html'))
    response.end()
  } else if(path === '/main.js'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
    response.write(fs.readFileSync('public/main.js'))
    response.end()
  } else if(path === '/style.css'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/css;charset=utf-8')
    response.write(fs.readFileSync('public/style.css'))
    response.end()
  } else {
    response.statusCode = 404
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(`你输入的路径不存在对应的内容`)
    response.end()
  }

  /******** 代码结束,下面不要看 ************/
})

server.listen(port)
console.log('监听 '   port   ' 成功n请用在空中转体720度然后用电饭煲打开 http://localhost:'   port)

使用html引用css

代码语言:javascript复制
<!DOCTYPE html>
<head>
    <link rel="stylesheet" href="/style.css">
    <title>曾老湿 AJAX 页面 2</title>
</head>
<body>
    <h1>曾老湿 AJAX 默认页面 2 </h1>
    <script src="/main.js"></script>
</body>

使用AJAX的方式来调用css,首先注释掉刚才html中的引用

总共有4个步骤: 1.打开冰箱门 2.把大象切成块 3.把切好的装入冰箱 4.关上冰箱门 ...

对不起,乱入了。

总共有4个步骤: 1.创建HttpRequest对象(全称是:XMLHTTPRequest) 2.调用对象的open方法 3.监听对象的onload & onerror事件(专业前端会改用onreadystatechange事件,在事件处理函数里操作CSS文件内容) 4.调用对象的send方法(发送请求)

百度搜索MDN,直接CV工程师:https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/open

代码语言:javascript复制
// 1.创建对象
const request = new XMLHttpRequest()

// 2.调用open方法
request.open('GET','/style.css')

// 3.监听onload成功事件,onerror失败事件
request.onload = () => {
    console.log('卧槽,成功了')
}
request.onerror = () => {
    console.log('阿西吧,失败了')
}

// 4.发送send请求
request.send()

直接请求,我们看不出任何效果,所以我们需要在页面上添加一个按钮。

代码语言:javascript复制
<!DOCTYPE html>
<head>
    <!-- <link rel="stylesheet" href="/style.css"> -->
    <title>曾老湿 AJAX 页面 2</title>
</head>
<body>
    <h1>曾老湿 AJAX 默认页面 2 </h1>
    <p>
        <button id="getCSS">请求 CSS</button>
    </p>
    <script src="/main.js"></script>
</body>
代码语言:javascript复制
getCSS.onclick = () => {
    const request = new XMLHttpRequest()
    request.open('GET','/style.css')
    request.onload = () => {
        console.log('卧槽,成功了')
    }
    request.onerror = () => {
        console.log('阿西吧,失败了')
    }
    request.send()
}

如图所示,请求是成功了,但是页面的字体颜色没有改变,那么我们需要使用js把CSS的内容插入到html的身体里面。

代码语言:javascript复制
getCSS.onclick = () => {
    const request = new XMLHttpRequest()
    request.open('GET','/style.css')
    request.onload = () => {
        //创建style标签
        const style = document.createElement('style')
        //填写style内容
        style.innerHTML = request.response
        //插入头部
        document.head.appendChild(style)
    }
    request.onerror = () => {
        console.log('阿西吧,失败了')
    }
    request.send()
}

以上就是通过AJAX的方式请求CSS

使用AJAX加载js

同样我们还是用老方法和AJAX的方法。首先创建一个js文件,然后使用index.html调用。

代码语言:javascript复制
console.log('我是 zls.js')
代码语言:javascript复制
<!DOCTYPE html>
<head>
    <!-- <link rel="stylesheet" href="/style.css"> -->
    <title>曾老湿 AJAX 页面 2</title>
</head>
<body>
    <h1>曾老湿 AJAX 默认页面 2 </h1>
    <p>
        <button id="getCSS">请求 CSS</button>
    </p>
    <script src="/main.js"></script>
    <script src="/zls.js"></script>
</body>
代码语言:javascript复制
var http = require('http')
var fs = require('fs')
var url = require('url')
var port = process.argv[2]

if(!port){
  console.log('请指定端口号好不啦?nnode server.js 8888 这样不会吗?')
  process.exit(1)
}

var server = http.createServer(function(request, response){
  var parsedUrl = url.parse(request.url, true)
  var pathWithQuery = request.url 
  var queryString = ''
  if(pathWithQuery.indexOf('?') >= 0){ queryString = pathWithQuery.substring(pathWithQuery.indexOf('?')) }
  var path = parsedUrl.pathname
  var query = parsedUrl.query
  var method = request.method

  /******** 从这里开始看,上面不要看 ************/

  console.log('有个傻子发请求过来啦!路径(带查询参数)为:'   pathWithQuery)

  if(path === '/index.html'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    var accept = request.headers["accept"];
    console.log("accept:");
    console.log(accept);
    response.write(fs.readFileSync('public/index.html'))
    response.end()
  } else if(path === '/main.js'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
    response.write(fs.readFileSync('public/main.js'))
    response.end()
  } else if(path === '/style.css'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/css;charset=utf-8')
    response.write(fs.readFileSync('public/style.css'))
    response.end()
  } else if(path === '/zls.js'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
    response.write(fs.readFileSync('public/zls.js'))
    response.end()
  } else {
    response.statusCode = 404
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(`你输入的路径不存在对应的内容`)
    response.end()
  }

  /******** 代码结束,下面不要看 ************/
})

server.listen(port)
console.log('监听 '   port   ' 成功n请用在空中转体720度然后用电饭煲打开 http://localhost:'   port)

使用AJAX的方法

注释掉,源代码的引用,添加一个按钮

代码语言:javascript复制
<!DOCTYPE html>
<head>
    <!-- <link rel="stylesheet" href="/style.css"> -->
    <title>曾老湿 AJAX 页面 2</title>
</head>
<body>
    <h1>曾老湿 AJAX 默认页面 2 </h1>
    <p>
        <button id="getCSS">请求 CSS</button>
        <button id="getJS">请求 JS</button>
    </p>
    <script src="/main.js"></script>
    <!-- <script src="/zls.js"></script> -->
</body>

还是上面的4个步骤...

代码语言:javascript复制
getJS.onclick = () =>{
    const request = new XMLHttpRequest()
    request.open('GET','/zls.js')
    request.onload = () => {
        console.log('卧槽,JS请求成功了')
    }
    request.onerror = () => {
        console.log('阿西吧,JS失败了')
    }
    request.send()
}

刚才我们执行了style.css,现在我们也执行js

代码语言:javascript复制
getJS.onclick = () =>{
    const request = new XMLHttpRequest()
    request.open('GET','/zls.js')
    request.onload = () => {
        const script = document.createElement('script')
        script.innerHTML = request.response
        document.body.appendChild(script)
    }
    request.onerror = () => {
        console.log('阿西吧,JS失败了')
    }
    request.send()
}

使用AJAX加载HTML

同样,我们先添加一个html的按钮

代码语言:javascript复制
<!DOCTYPE html>
<head>
    <!-- <link rel="stylesheet" href="/style.css"> -->
    <title>曾老湿 AJAX 页面 2</title>
</head>
<body>
    <h1>曾老湿 AJAX 默认页面 2 </h1>
    <p>
        <button id="getCSS">请求 CSS</button>
        <button id="getJS">请求 JS</button>
        <button id="getHTML">请求 HTML</button>
    </p>
    <script src="/main.js"></script>
    <!-- <script src="/zls.js"></script> -->
</body>

在server中添加一个请求,然后创建zls.html

代码语言:javascript复制
var http = require('http')
var fs = require('fs')
var url = require('url')
var port = process.argv[2]

if(!port){
  console.log('请指定端口号好不啦?nnode server.js 8888 这样不会吗?')
  process.exit(1)
}

var server = http.createServer(function(request, response){
  var parsedUrl = url.parse(request.url, true)
  var pathWithQuery = request.url 
  var queryString = ''
  if(pathWithQuery.indexOf('?') >= 0){ queryString = pathWithQuery.substring(pathWithQuery.indexOf('?')) }
  var path = parsedUrl.pathname
  var query = parsedUrl.query
  var method = request.method

  /******** 从这里开始看,上面不要看 ************/

  console.log('有个傻子发请求过来啦!路径(带查询参数)为:'   pathWithQuery)

  if(path === '/index.html'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    var accept = request.headers["accept"];
    console.log("accept:");
    console.log(accept);
    response.write(fs.readFileSync('public/index.html'))
    response.end()
  } else if(path === '/main.js'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
    response.write(fs.readFileSync('public/main.js'))
    response.end()
  } else if(path === '/style.css'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/css;charset=utf-8')
    response.write(fs.readFileSync('public/style.css'))
    response.end()
  } else if(path === '/zls.js'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
    response.write(fs.readFileSync('public/zls.js'))
    response.end()
  } else if(path === '/zls.html'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(fs.readFileSync('public/zls.html'))
    response.end()
  } else {
    response.statusCode = 404
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(`你输入的路径不存在对应的内容`)
    response.end()
  }

  /******** 代码结束,下面不要看 ************/
})

server.listen(port)
console.log('监听 '   port   ' 成功n请用在空中转体720度然后用电饭煲打开 http://localhost:'   port)

代码语言:javascript复制
<div style="background: green; border:1px solid red; width: 300px; height: 300px;">
    这里是曾老湿 动态内容
</div>

添加点击事件

代码语言:javascript复制
getHTML.onclick = () =>{
    const request = new XMLHttpRequest()
    request.open('GET','/zls.html')
    request.onload = () =>{}
    request.onerror = () =>{}
    request.send()
}

我们确实请求到html,现在的想法就是,当我点击了按钮了,我们就把html放在当前页面上。

代码语言:javascript复制
getHTML.onclick = () =>{
    const request = new XMLHttpRequest()
    request.open('GET','/zls.html')
    request.onload = () =>{
        const div = document.createElement('div')
        div.innerHTML = request.response
        document.body.appendChild(div)
    }
    request.onerror = () =>{}
    request.send()
}

触发错误事件

前面我写到一句话,专业的前端,不会使用onload和onerror,而是会使用onreadystatechange,因为onerror是在AJAX出来之前就已经存在的,所以对AJAX的兼容性不好,于是我们需要使用onreadystatechange事件,来监听。还是一样,我们通过MDN了解一下onreadystatechange:https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/onreadystatechange

上面有一句话我们标重点:只要 readyState 属性发生变化,就会调用相应的处理函数 那到底什么是readyState呢?https://developer.mozilla.org/zh-CN/docs/Web/API/XMLHttpRequest/readyState

状态

描述

0

UNSENT

代理被创建,但尚未调用 open() 方法。

1

OPENED

open() 方法已经被调用。

2

HEADERS_RECEIVED

send() 方法已经被调用,并且头部和状态已经可获得。

3

LOADING

下载中; responseText 属性已经包含部分数据。

4

DONE

下载操作已完成。

用代码查看这个过程。

代码语言:javascript复制
getCSS.onclick = () => {
    const request = new XMLHttpRequest()
    request.open('GET','/style.css')
    request.onreadystatechange = () => {
        console.log(request.readyState)
    }
    request.send()
}

哎?为啥是2 , 3 ,4 请问0和1去哪里了?

如果有上面这个疑问的童鞋,你484没有好好,仔细的看代码?484傻?

代码语言:javascript复制
// 这一行就是  0
const request = new XMLHttpRequest()

// 调用open了,这一行就是1啊
    request.open('GET','/style.css')

接下来我们就用这个 onreadystatechange 来判断。

代码语言:javascript复制
getCSS.onclick = () => {
    const request = new XMLHttpRequest()
    request.open('GET','/style.css')
    request.onreadystatechange = () => {
        console.log(request.readyState)
        if(request.readyState === 4){
            console.log('下载完成惹...')
        }
    }
    request.send()
}

一次很嗲的请求。

接下来,我们把如果是4要做的事情放进去,就是让字体变成蓝色

代码语言:javascript复制
getCSS.onclick = () => {
    const request = new XMLHttpRequest()
    request.open('GET','/style.css')
    request.onreadystatechange = () => {
        console.log(request.readyState)
        if(request.readyState === 4){
            console.log('下载完成惹...')
            //创建style标签
            const style = document.createElement('style')
            //填写style内容
            style.innerHTML = request.response
            //插入头部
            document.head.appendChild(style)
        }
    }
    request.send()
}

我们来手贱一下,故意把代码路径改错,再访问一次。仔细看style.css改成了stlye.css

代码语言:javascript复制
getCSS.onclick = () => {
    const request = new XMLHttpRequest()
    request.open('GET','/stlye.css')
    request.onreadystatechange = () => {
        console.log(request.readyState)
        if(request.readyState === 4){
            console.log('下载完成惹...')
            //创建style标签
            const style = document.createElement('style')
            //填写style内容
            style.innerHTML = request.response
            //插入头部
            document.head.appendChild(style)
        }
    }
    request.send()
}

还是显示下载完成惹,但是...字体颜色没变。接下来我们使用request.status查看一下状态码。

代码语言:javascript复制
getCSS.onclick = () => {
    const request = new XMLHttpRequest()
    request.open('GET','/stlye.css')
    request.onreadystatechange = () => {
        console.log(request.readyState)
        if(request.readyState === 4){
            console.log('下载完成惹...')
            console.log(request.status)
            //创建style标签
            const style = document.createElement('style')
            //填写style内容
            style.innerHTML = request.response
            //插入头部
            document.head.appendChild(style)
        }
    }
    request.send()
}

可以看到,状态码是404,于是乎,我们就可以用这个状态码来做文章了。

代码语言:javascript复制
getCSS.onclick = () => {
    const request = new XMLHttpRequest()
    request.open('GET','/stlye.css')
    request.onreadystatechange = () => {
        console.log(request.readyState)
        if(request.readyState === 4){
            if(request.status >= 200 && request.status <300){
                //创建style标签
                const style = document.createElement('style')
                //填写style内容
                style.innerHTML = request.response
                //插入头部
                document.head.appendChild(style)
            }else{
                alert('兄dei,你的 CSS 加载失败惹...')
            }
        } 
    }
    request.send()
}

使用AJAX加载XML

同样,我们还要去改server.js,写一个加载XML的路由。

代码语言:javascript复制
var http = require('http')
var fs = require('fs')
var url = require('url')
var port = process.argv[2]

if(!port){
  console.log('请指定端口号好不啦?nnode server.js 8888 这样不会吗?')
  process.exit(1)
}

var server = http.createServer(function(request, response){
  var parsedUrl = url.parse(request.url, true)
  var pathWithQuery = request.url 
  var queryString = ''
  if(pathWithQuery.indexOf('?') >= 0){ queryString = pathWithQuery.substring(pathWithQuery.indexOf('?')) }
  var path = parsedUrl.pathname
  var query = parsedUrl.query
  var method = request.method

  /******** 从这里开始看,上面不要看 ************/

  console.log('有个傻子发请求过来啦!路径(带查询参数)为:'   pathWithQuery)

  if(path === '/index.html'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    var accept = request.headers["accept"];
    console.log("accept:");
    console.log(accept);
    response.write(fs.readFileSync('public/index.html'))
    response.end()
  } else if(path === '/main.js'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
    response.write(fs.readFileSync('public/main.js'))
    response.end()
  } else if(path === '/style.css'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/css;charset=utf-8')
    response.write(fs.readFileSync('public/style.css'))
    response.end()
  } else if(path === '/zls.js'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
    response.write(fs.readFileSync('public/zls.js'))
    response.end()
  } else if(path === '/zls.html'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(fs.readFileSync('public/zls.html'))
    response.end()
  } else if(path === '/zls.xml'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/xml;charset=utf-8')
    response.write(fs.readFileSync('public/zls.xml'))
    response.end()
  } else {
    response.statusCode = 404
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(`你输入的路径不存在对应的内容`)
    response.end()
  }

  /******** 代码结束,下面不要看 ************/
})

server.listen(port)
console.log('监听 '   port   ' 成功n请用在空中转体720度然后用电饭煲打开 http://localhost:'   port)

接下来创建 XML,但是好像不太会写XML的代码...还是求助MDN:https://developer.mozilla.org/zh-CN/docs/Web/XML/XML_Introduction

随便找一段代码。

代码语言:javascript复制
<?xml version="1.0" encoding="UTF-8"?>
<message>
    <warning>
         Hello World
    </warning>
</message>

然后在html中添加一个按钮

代码语言:javascript复制
<!DOCTYPE html>
<head>
    <!-- <link rel="stylesheet" href="/style.css"> -->
    <title>曾老湿 AJAX 页面 2</title>
</head>
<body>
    <h1>曾老湿 AJAX 默认页面 2 </h1>
    <p>
        <button id="getCSS">请求 CSS</button>
        <button id="getJS">请求 JS</button>
        <button id="getHTML">请求 HTML</button>
        <button id="getXML">请求 XML</button>
    </p>
    <script src="/main.js"></script>
    <!-- <script src="/zls.js"></script> -->
</body>
代码语言:javascript复制
getXML.onclick = () =>{
    const request = new XMLHttpRequest()
    request.open('GET','/zls.xml')
    request.onreadystatechange = () =>{
        if(request.readyState === 4){
            if(request.status >= 200  && request.status <300){
                console.log(request.response)
            }
        }
    }
    request.send()
}

AJAX可以直接使用XML,我们现在使用request.response对于XML来说,我们可以直接request.responeXML得到一个数组,然后直接使用这个数组中的元素就可以直接得到Hello World

代码语言:javascript复制
getXML.onclick = () =>{
    const request = new XMLHttpRequest()
    request.open('GET','/zls.xml')
    request.onreadystatechange = () =>{
        if(request.readyState === 4 ){
            if(request.status >= 200 && request.status < 300){
                const dom = request.responseXML
                const text  = dom.getElementsByTagName('warning')[0].textContent
                console.log(text.trim())
            }
        }
    }
    request.send()
}

但是XML刚出来没两年,有一个新的语言,替代了XML,那就是Json,所以我们需要实现 ,把Json加载到页面。

在我们加载Json的之前 ,我们先来做个总结

总结:

HTTP是个框,什么都能往里装 1.可以装HTML、CSS、JS、XML... 2.只要设置正确的Content-Type,就什么都能解析 3.只要知道如何解析这些内容,就可以使用这些内容

解析方法: 1.得到CSS之后,生成style标签 2.得到JS之后,生成script标签 3.得到HTML之后使用 innerHTML 和 DOM API 4.得到XML之后使用 responseXML 和 DOM API 不同类型的数据有不同类型的解析方法

加载JSON

JSON的全拼:JavaScript Object Notation JS对象标记语言。

JSON是一门语言,跟HTML、CSS、JS一样,是一门独立的语言,但是它不是变成语言,是标记语言。

最简单的语言没有之一...5秒钟学会一门语言。

JSON官网:TP

JSON这门语言是借(chao)鉴(xi)JS

铁轨图:

对象是一个无序的“‘名称/值’对”集合。一个对象以 {左括号 开始, }右括号 结束。每个“名称”后跟一个 :冒号 ;“‘名称/值’ 对”之间使用 ,逗号 分隔。

值(value)可以是双引号括起来的字符串(string)、数值(number)、true、false、 null、对象(object)或者数组(array)。这些结构可以嵌套。

数组是值(value)的有序集合。一个数组以 [左中括号 开始, ]右中括号 结束。值之间使用 ,逗号 分隔。

字符串(string)是由双引号包围的任意数量Unicode字符的集合,使用反斜线转义。一个字符(character)即一个单独的字符串(character string)。

字符串(string)与C或者Java的字符串非常相似。

数值(number)也与C或者Java的数值非常相似。除去未曾使用的八进制与十六进制格式。除去一些编码细节。

空白可以加入到任何符号之间。 以下描述了完整的语言。

话不多说,我们直接来加载JSON,还是一样,在服务端多创建一个路由。

代码语言:javascript复制
var http = require('http')
var fs = require('fs')
var url = require('url')
var port = process.argv[2]

if(!port){
  console.log('请指定端口号好不啦?nnode server.js 8888 这样不会吗?')
  process.exit(1)
}

var server = http.createServer(function(request, response){
  var parsedUrl = url.parse(request.url, true)
  var pathWithQuery = request.url 
  var queryString = ''
  if(pathWithQuery.indexOf('?') >= 0){ queryString = pathWithQuery.substring(pathWithQuery.indexOf('?')) }
  var path = parsedUrl.pathname
  var query = parsedUrl.query
  var method = request.method

  /******** 从这里开始看,上面不要看 ************/

  console.log('有个傻子发请求过来啦!路径(带查询参数)为:'   pathWithQuery)

  if(path === '/index.html'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    var accept = request.headers["accept"];
    console.log("accept:");
    console.log(accept);
    response.write(fs.readFileSync('public/index.html'))
    response.end()
  } else if(path === '/main.js'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
    response.write(fs.readFileSync('public/main.js'))
    response.end()
  } else if(path === '/style.css'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/css;charset=utf-8')
    response.write(fs.readFileSync('public/style.css'))
    response.end()
  } else if(path === '/zls.js'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
    response.write(fs.readFileSync('public/zls.js'))
    response.end()
  } else if(path === '/zls.html'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(fs.readFileSync('public/zls.html'))
    response.end()
  } else if(path === '/zls.xml'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/xml;charset=utf-8')
    response.write(fs.readFileSync('public/zls.xml'))
    response.end()
  } else if(path === '/zls.json'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'application/json;charset=utf-8')
    // response.setHeader('Content-Type', 'text/json;charset=utf-8')
    response.write(fs.readFileSync('public/zls.json'))
    response.end()
  } else {
    response.statusCode = 404
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(`你输入的路径不存在对应的内容`)
    response.end()
  }

  /******** 代码结束,下面不要看 ************/
})

server.listen(port)
console.log('监听 '   port   ' 成功n请用在空中转体720度然后用电饭煲打开 http://localhost:'   port)

写一个JSON

代码语言:javascript复制
{
    "name":"zls",
    "age":18,
    "salary":"100w",
    "house":null,
    "car":null
}

加个按钮

代码语言:javascript复制
<!DOCTYPE html>
<head>
    <!-- <link rel="stylesheet" href="/style.css"> -->
    <title>曾老湿 AJAX 页面 2</title>
</head>
<body>
    <h1>曾老湿 AJAX 默认页面 2 </h1>
    <p>
        <button id="getCSS">请求 CSS</button>
        <button id="getJS">请求 JS</button>
        <button id="getHTML">请求 HTML</button>
        <button id="getXML">请求 XML</button>
        <button id="getJSON">请求 JSON</button>
    </p>
    <script src="/main.js"></script>
    <!-- <script src="/zls.js"></script> -->
</body>

监听点击事件

代码语言:javascript复制
getJSON.onclick = () =>{
    const request = new XMLHttpRequest()
    request.open('GET','/zls.json')
    request.onreadystatechange = () =>{
        if(request.readyState === 4 ){
            if(request.status >= 200 && request.status < 300){
                console.log(request.response)
            }
        }
    }
    request.send()
}

把JSON变成我们想要的JS对象 ,这也是每种语言,不管是JAVA、Python、C...等语言都带的一种功能,叫做反序列化。

代码语言:javascript复制
getJSON.onclick = () =>{
    const request = new XMLHttpRequest()
    request.open('GET','/zls.json')
    request.onreadystatechange = () =>{
        if(request.readyState === 4 ){
            if(request.status >= 200 && request.status < 300){
                console.log(request.response)
                const object = JSON.parse(request.response)
                console.log(object)
            }
        }
    }
    request.send()
}

这样一来JS这门语言就可以使用这个数据了,JSON是一个桥梁,比如Python代码获取到的数据可以保存成JSON的格式,这个过程叫做序列化,然后拿到数据,JS前端代码就可以反序列化成JS的格式来处理数据,这就是 前端和后端沟通的桥梁。

那么接下来,我们来使用这个数据。我们先把HTML改一下

代码语言:javascript复制
<!DOCTYPE html>
<head>
    <!-- <link rel="stylesheet" href="/style.css"> -->
    <title>曾老湿 AJAX 页面 2</title>
</head>
<body>
    <h1>AJAX Hello <span id="myName"></span> </h1>
    <p>
        <button id="getCSS">请求 CSS</button>
        <button id="getJS">请求 JS</button>
        <button id="getHTML">请求 HTML</button>
        <button id="getXML">请求 XML</button>
        <button id="getJSON">请求 JSON</button>
    </p>
    <script src="/main.js"></script>
    <!-- <script src="/zls.js"></script> -->
</body>

获取JSON数据

代码语言:javascript复制
getJSON.onclick = () =>{
    const request = new XMLHttpRequest()
    request.open('GET','/zls.json')
    request.onreadystatechange = () =>{
        if(request.readyState === 4 ){
            if(request.status >= 200 && request.status < 300){
                console.log(request.response)
                const object = JSON.parse(request.response)
                myName.textContent = object.name
            }
        }
    }
    request.send()
}

代码语言:javascript复制
## window.JSON

# 1.JSON.parse
# 将符合JSON语法的字符串转换成JS对应类型的数据
# JSON字符串 => JS数据
# 由于JSON只有六中类型,所以转成的数据也只有6种
# 如果不符合JSON语法 ,则直接抛出一个 Error对象
# 一般用 try catch 捕获错误 

// 错误写法
JSON.parse(`{'name':'zls'}`)
// 捕获错误
try{
    object = JSON.parse(`{'name':'zls'}`)
}catch(error){
    console.log('出错了,错误详情是:')
    console.log(error)
    object = {'name':'no name'}
}

# 2.JSON.stringify
# 是JSON.parse的逆运算
# JS数据 => JSON字符串
# 由于JS的数据类型比JSON多,所以不一定能成功
# 如果失败就抛出一个Error对象

综合应用-加载分页

加载分页本来应该放在数据库里面,现在我们放到文件里,首先在VScode中创建一个目录名字叫db,假装是个数据库,然后在目录中创建3个json文件,分别叫做page1.json,page2.json,page3.json

page1.json

代码语言:javascript复制
[
    {"id":1},
    {"id":2},
    {"id":3},
    {"id":4},
    {"id":5},
    {"id":6},
    {"id":7},
    {"id":8},
    {"id":9},
    {"id":10}
]

page2.json

代码语言:javascript复制
[
    {"id":11},
    {"id":12},
    {"id":13},
    {"id":14},
    {"id":15},
    {"id":16},
    {"id":17},
    {"id":18},
    {"id":19},
    {"id":20}
]

page3.json

代码语言:javascript复制
[
    {"id":21},
    {"id":22},
    {"id":23},
    {"id":24},
    {"id":25},
    {"id":26},
    {"id":27},
    {"id":28},
    {"id":29},
    {"id":30}
]

修改html,添加第一页内容,静态加载

代码语言:javascript复制
<!DOCTYPE html>
<head>
    <!-- <link rel="stylesheet" href="/style.css"> -->
    <title>曾老湿 AJAX 页面 2</title>
</head>
<body>
    <h1>AJAX Hello <span id="myName"></span> </h1>
    <p>
        <button id="getCSS">请求 CSS</button>
        <button id="getJS">请求 JS</button>
        <button id="getHTML">请求 HTML</button>
        <button id="getXML">请求 XML</button>
        <button id="getJSON">请求 JSON</button>
    </p>

    <div>
        {{ page1 }}
    </div>

    <script src="/main.js"></script>
    <!-- <script src="/zls.js"></script> -->
</body>

server.js中读取内容,替换html中的page1占位符

代码语言:javascript复制
var http = require('http')
var fs = require('fs')
var url = require('url')
var port = process.argv[2]

if(!port){
  console.log('请指定端口号好不啦?nnode server.js 8888 这样不会吗?')
  process.exit(1)
}

var server = http.createServer(function(request, response){
  var parsedUrl = url.parse(request.url, true)
  var pathWithQuery = request.url 
  var queryString = ''
  if(pathWithQuery.indexOf('?') >= 0){ queryString = pathWithQuery.substring(pathWithQuery.indexOf('?')) }
  var path = parsedUrl.pathname
  var query = parsedUrl.query
  var method = request.method

  /******** 从这里开始看,上面不要看 ************/

  console.log('有个傻子发请求过来啦!路径(带查询参数)为:'   pathWithQuery)

  if(path === '/index.html'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    var accept = request.headers["accept"];
    console.log("accept:");
    console.log(accept);
    let string = fs.readFileSync('public/index.html').toString()
    const page1 = fs.readFileSync('db/page1.json').toString()
    string = string.replace('{{ page1 }}',page1)
    response.write(string)
    response.end()
  } else if(path === '/main.js'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
    response.write(fs.readFileSync('public/main.js'))
    response.end()
  } else if(path === '/style.css'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/css;charset=utf-8')
    response.write(fs.readFileSync('public/style.css'))
    response.end()
  } else if(path === '/zls.js'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
    response.write(fs.readFileSync('public/zls.js'))
    response.end()
  } else if(path === '/zls.html'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(fs.readFileSync('public/zls.html'))
    response.end()
  } else if(path === '/zls.xml'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/xml;charset=utf-8')
    response.write(fs.readFileSync('public/zls.xml'))
    response.end()
  } else if(path === '/zls.json'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/json;charset=utf-8')
    response.write(fs.readFileSync('public/zls.json'))
    response.end()
  } else {
    response.statusCode = 404
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(`你输入的路径不存在对应的内容`)
    response.end()
  }

  /******** 代码结束,下面不要看 ************/
})

server.listen(port)
console.log('监听 '   port   ' 成功n请用在空中转体720度然后用电饭煲打开 http://localhost:'   port)

我们可以把这个JSON数据转化成JS的数据,这部分内容可以不懂,很古老的技术了...

代码语言:javascript复制
  if(path === '/index.html'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    var accept = request.headers["accept"];
    console.log("accept:");
    console.log(accept);
    let string = fs.readFileSync('public/index.html').toString()
    const page1 = fs.readFileSync('db/page1.json').toString()
    const array = JSON.parse(page1)
    const result = array.map(item=>`<li>${item.id}</li>`).join('')
    string = string.replace('{{ page1 }}',`<ul id='zls'>${result}</ul>`)
    response.write(string)
    response.end()
  } 

添加下一页按钮

代码语言:javascript复制
<!DOCTYPE html>
<head>
    <!-- <link rel="stylesheet" href="/style.css"> -->
    <title>曾老湿 AJAX 页面 2</title>
</head>
<body>
    <h1>AJAX Hello <span id="myName"></span> </h1>
    <p>
        <button id="getCSS">请求 CSS</button>
        <button id="getJS">请求 JS</button>
        <button id="getHTML">请求 HTML</button>
        <button id="getXML">请求 XML</button>
        <button id="getJSON">请求 JSON</button>
        <button id="getPage">下一页</button>
    </p>

    <div>
        {{ page1 }}
    </div>

    <script src="/main.js"></script>
    <!-- <script src="/zls.js"></script> -->
</body>

添加请求page2的路由

代码语言:javascript复制
var http = require('http')
var fs = require('fs')
var url = require('url')
var port = process.argv[2]

if(!port){
  console.log('请指定端口号好不啦?nnode server.js 8888 这样不会吗?')
  process.exit(1)
}

var server = http.createServer(function(request, response){
  var parsedUrl = url.parse(request.url, true)
  var pathWithQuery = request.url 
  var queryString = ''
  if(pathWithQuery.indexOf('?') >= 0){ queryString = pathWithQuery.substring(pathWithQuery.indexOf('?')) }
  var path = parsedUrl.pathname
  var query = parsedUrl.query
  var method = request.method

  /******** 从这里开始看,上面不要看 ************/

  console.log('有个傻子发请求过来啦!路径(带查询参数)为:'   pathWithQuery)

  if(path === '/index.html'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    var accept = request.headers["accept"];
    console.log("accept:");
    console.log(accept);
    let string = fs.readFileSync('public/index.html').toString()
    const page1 = fs.readFileSync('db/page1.json').toString()
    const array = JSON.parse(page1)
    const result = array.map(item=>`<li>${item.id}</li>`).join('')
    string = string.replace('{{ page1 }}',`<ul id='zls'>${result}</ul>`)
    response.write(string)
    response.end()
  } else if(path === '/main.js'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
    response.write(fs.readFileSync('public/main.js'))
    response.end()
  } else if(path === '/style.css'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/css;charset=utf-8')
    response.write(fs.readFileSync('public/style.css'))
    response.end()
  } else if(path === '/zls.js'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
    response.write(fs.readFileSync('public/zls.js'))
    response.end()
  } else if(path === '/zls.html'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(fs.readFileSync('public/zls.html'))
    response.end()
  } else if(path === '/zls.xml'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/xml;charset=utf-8')
    response.write(fs.readFileSync('public/zls.xml'))
    response.end()
  } else if(path === '/zls.json'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/json;charset=utf-8')
    response.write(fs.readFileSync('public/zls.json'))
    response.end()
  } else if(path === '/page2'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/json;charset=utf-8')
    response.write(fs.readFileSync('db/page2.json'))
    response.end()
  } else {
    response.statusCode = 404
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(`你输入的路径不存在对应的内容`)
    response.end()
  }

  /******** 代码结束,下面不要看 ************/
})

server.listen(port)
console.log('监听 '   port   ' 成功n请用在空中转体720度然后用电饭煲打开 http://localhost:'   port)

添加监听

代码语言:javascript复制
getPage.onclick = () =>{
    const request = new XMLHttpRequest()
    request.open('GET','/page2')
    request.onreadystatechange = () =>{
        if(request.readyState === 4 ){
            if(request.status >= 200 && request.status < 300){
                console.log(request.response)
            }
        }
    }
    request.send()
}

拿到了结果,但是没有渲染页面...

代码语言:javascript复制
getPage.onclick = () =>{
    const request = new XMLHttpRequest()
    request.open('GET','/page2')
    request.onreadystatechange = () =>{
        if(request.readyState === 4 ){
            if(request.status >= 200 && request.status < 300){
                const array = JSON.parse(request.response)
                array.forEach(item=>{
                    const li = document.createElement('li')
                    li.textContent = item.id
                    zls.appendChild(li)
                })
            }
        }
    }
    request.send()
}

但是当我第二次请求下一页的时候...mmp,出事了,还是11-20

所以我们要把代码中的page2改成变量,不要写死。

代码语言:javascript复制
let n = 1
getPage.onclick = () =>{
    const request = new XMLHttpRequest()
    request.open('GET',`/page${n 1}`)
    request.onreadystatechange = () =>{
        if(request.readyState === 4 ){
            if(request.status >= 200 && request.status < 300){
                const array = JSON.parse(request.response)
                array.forEach(item=>{
                    const li = document.createElement('li')
                    li.textContent = item.id
                    zls.appendChild(li)
                })
                n =1
            }
        }
    }
    request.send()
}

点击第二次的时候请求page3报错了,我们需要在server.js上添加路由

代码语言:javascript复制
var http = require('http')
var fs = require('fs')
var url = require('url')
var port = process.argv[2]

if(!port){
  console.log('请指定端口号好不啦?nnode server.js 8888 这样不会吗?')
  process.exit(1)
}

var server = http.createServer(function(request, response){
  var parsedUrl = url.parse(request.url, true)
  var pathWithQuery = request.url 
  var queryString = ''
  if(pathWithQuery.indexOf('?') >= 0){ queryString = pathWithQuery.substring(pathWithQuery.indexOf('?')) }
  var path = parsedUrl.pathname
  var query = parsedUrl.query
  var method = request.method

  /******** 从这里开始看,上面不要看 ************/

  console.log('有个傻子发请求过来啦!路径(带查询参数)为:'   pathWithQuery)

  if(path === '/index.html'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    var accept = request.headers["accept"];
    console.log("accept:");
    console.log(accept);
    let string = fs.readFileSync('public/index.html').toString()
    const page1 = fs.readFileSync('db/page1.json').toString()
    const array = JSON.parse(page1)
    const result = array.map(item=>`<li>${item.id}</li>`).join('')
    string = string.replace('{{ page1 }}',`<ul id='zls'>${result}</ul>`)
    response.write(string)
    response.end()
  } else if(path === '/main.js'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
    response.write(fs.readFileSync('public/main.js'))
    response.end()
  } else if(path === '/style.css'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/css;charset=utf-8')
    response.write(fs.readFileSync('public/style.css'))
    response.end()
  } else if(path === '/zls.js'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
    response.write(fs.readFileSync('public/zls.js'))
    response.end()
  } else if(path === '/zls.html'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(fs.readFileSync('public/zls.html'))
    response.end()
  } else if(path === '/zls.xml'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/xml;charset=utf-8')
    response.write(fs.readFileSync('public/zls.xml'))
    response.end()
  } else if(path === '/zls.json'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/json;charset=utf-8')
    response.write(fs.readFileSync('public/zls.json'))
    response.end()
  } else if(path === '/page2'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/json;charset=utf-8')
    response.write(fs.readFileSync('db/page2.json'))
    response.end()
  } else if(path === '/page3'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/json;charset=utf-8')
    response.write(fs.readFileSync('db/page3.json'))
    response.end()
  } else {
    response.statusCode = 404
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(`你输入的路径不存在对应的内容`)
    response.end()
  }

  /******** 代码结束,下面不要看 ************/
})

server.listen(port)
console.log('监听 '   port   ' 成功n请用在空中转体720度然后用电饭煲打开 http://localhost:'   port)

完整代码

server.js

代码语言:javascript复制
var http = require('http')
var fs = require('fs')
var url = require('url')
var port = process.argv[2]

if(!port){
  console.log('请指定端口号好不啦?nnode server.js 8888 这样不会吗?')
  process.exit(1)
}

var server = http.createServer(function(request, response){
  var parsedUrl = url.parse(request.url, true)
  var pathWithQuery = request.url 
  var queryString = ''
  if(pathWithQuery.indexOf('?') >= 0){ queryString = pathWithQuery.substring(pathWithQuery.indexOf('?')) }
  var path = parsedUrl.pathname
  var query = parsedUrl.query
  var method = request.method

  /******** 从这里开始看,上面不要看 ************/

  console.log('有个傻子发请求过来啦!路径(带查询参数)为:'   pathWithQuery)

  if(path === '/index.html'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    var accept = request.headers["accept"];
    console.log("accept:");
    console.log(accept);
    let string = fs.readFileSync('public/index.html').toString()
    const page1 = fs.readFileSync('db/page1.json').toString()
    const array = JSON.parse(page1)
    const result = array.map(item=>`<li>${item.id}</li>`).join('')
    string = string.replace('{{ page1 }}',`<ul id='zls'>${result}</ul>`)
    response.write(string)
    response.end()
  } else if(path === '/main.js'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
    response.write(fs.readFileSync('public/main.js'))
    response.end()
  } else if(path === '/style.css'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/css;charset=utf-8')
    response.write(fs.readFileSync('public/style.css'))
    response.end()
  } else if(path === '/zls.js'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/javascript;charset=utf-8')
    response.write(fs.readFileSync('public/zls.js'))
    response.end()
  } else if(path === '/zls.html'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(fs.readFileSync('public/zls.html'))
    response.end()
  } else if(path === '/zls.xml'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/xml;charset=utf-8')
    response.write(fs.readFileSync('public/zls.xml'))
    response.end()
  } else if(path === '/zls.json'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/json;charset=utf-8')
    response.write(fs.readFileSync('public/zls.json'))
    response.end()
  } else if(path === '/page2'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/json;charset=utf-8')
    response.write(fs.readFileSync('db/page2.json'))
    response.end()
  } else if(path === '/page3'){
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/json;charset=utf-8')
    response.write(fs.readFileSync('db/page3.json'))
    response.end()
  } else {
    response.statusCode = 404
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(`你输入的路径不存在对应的内容`)
    response.end()
  }

  /******** 代码结束,下面不要看 ************/
})

server.listen(port)
console.log('监听 '   port   ' 成功n请用在空中转体720度然后用电饭煲打开 http://localhost:'   port)

index.html

代码语言:javascript复制
<!DOCTYPE html>
<head>
    <!-- <link rel="stylesheet" href="/style.css"> -->
    <title>曾老湿 AJAX 页面 2</title>
</head>
<body>
    <h1>AJAX Hello <span id="myName"></span> </h1>
    <p>
        <button id="getCSS">请求 CSS</button>
        <button id="getJS">请求 JS</button>
        <button id="getHTML">请求 HTML</button>
        <button id="getXML">请求 XML</button>
        <button id="getJSON">请求 JSON</button>
        <button id="getPage">下一页</button>
    </p>

    <div>
        {{ page1 }}
    </div>

    <script src="/main.js"></script>
    <!-- <script src="/zls.js"></script> -->
</body>

main.js

代码语言:javascript复制
console.log('我是曾老湿main.js页面')

getCSS.onclick = () => {
    const request = new XMLHttpRequest()
    request.open('GET','/style.css')
    request.onreadystatechange = () => {
        console.log(request.readyState)
        if(request.readyState === 4){
            if(request.status >= 200 && request.status <300){
                //创建style标签
                const style = document.createElement('style')
                //填写style内容
                style.innerHTML = request.response
                //插入头部
                document.head.appendChild(style)
            }else{
                alert('兄dei,你的 CSS 加载失败惹...')
            }
        } 
    }
    request.send()
}

getJS.onclick = () =>{
    const request = new XMLHttpRequest()
    request.open('GET','/zls.js')
    request.onload = () => {
        const script = document.createElement('script')
        script.innerHTML = request.response
        document.body.appendChild(script)
    }
    request.onerror = () => {
        console.log('阿西吧,JS失败了')
    }
    request.send()
}

getHTML.onclick = () =>{
    const request = new XMLHttpRequest()
    request.open('GET','/zls.html')
    request.onload = () =>{
        const div = document.createElement('div')
        div.innerHTML = request.response
        document.body.appendChild(div)
    }
    request.onerror = () =>{}
    request.send()
}

getXML.onclick = () =>{
    const request = new XMLHttpRequest()
    request.open('GET','/zls.xml')
    request.onreadystatechange = () =>{
        if(request.readyState === 4 ){
            if(request.status >= 200 && request.status < 300){
                const dom = request.responseXML
                const text  = dom.getElementsByTagName('warning')[0].textContent
                console.log(text.trim())
            }
        }
    }
    request.send()
}

getJSON.onclick = () =>{
    const request = new XMLHttpRequest()
    request.open('GET','/zls.json')
    request.onreadystatechange = () =>{
        if(request.readyState === 4 ){
            if(request.status >= 200 && request.status < 300){
                console.log(request.response)
                const object = JSON.parse(request.response)
                myName.textContent = object.name
            }
        }
    }
    request.send()
}

let n = 1
getPage.onclick = () =>{
    const request = new XMLHttpRequest()
    request.open('GET',`/page${n 1}`)
    request.onreadystatechange = () =>{
        if(request.readyState === 4 ){
            if(request.status >= 200 && request.status < 300){
                const array = JSON.parse(request.response)
                array.forEach(item=>{
                    const li = document.createElement('li')
                    li.textContent = item.id
                    zls.appendChild(li)
                })
                    n =1
            }
        }
    }
    request.send()
}

style.css

代码语言:javascript复制
h1{
    color: blue;
}

zls.html

代码语言:javascript复制
<div style="background: green; border:1px solid red; width: 300px; height: 300px;">
    这里是曾老湿 动态内容
</div>

zls.js

代码语言:javascript复制
console.log('我是 zls.js')

zls.xml

代码语言:javascript复制
<?xml version="1.0" encoding="UTF-8"?>
<message>
    <warning>
         Hello World
    </warning>
</message>

zls.json

代码语言:javascript复制
{
    "name":"zls",
    "age":18,
    "salary":"100w",
    "house":null,
    "car":null
}

page1.json

代码语言:javascript复制
[
    {"id":1},
    {"id":2},
    {"id":3},
    {"id":4},
    {"id":5},
    {"id":6},
    {"id":7},
    {"id":8},
    {"id":9},
    {"id":10}
]

page2.json

代码语言:javascript复制
[
    {"id":11},
    {"id":12},
    {"id":13},
    {"id":14},
    {"id":15},
    {"id":16},
    {"id":17},
    {"id":18},
    {"id":19},
    {"id":20}
]

page3.json

代码语言:javascript复制
[
    {"id":21},
    {"id":22},
    {"id":23},
    {"id":24},
    {"id":25},
    {"id":26},
    {"id":27},
    {"id":28},
    {"id":29},
    {"id":30}
]

0 人点赞