3-1 Ajax请求的基本操作
1、准备两个文件 html js2、在终端打开 输入 node js文件名3、在浏览器中打开 http://127.0.0.1:8000/server
端口占用先将占用端口的文件关闭 CTRL+C或重新使用别的端口
html<button>点击</button><div id="result"></div><script>//获取元素const btn = document.getElementsByTagName('button')[0]var result = document.getElementById("result")//绑定事件btn.onclick = function(){//1、创建对象const xhr = new XMLHttpRequest()//2、初始化 设置请求方法和 urlxhr.open('GET','http://127.0.0.1:8000/server?a=100&b=200&c=300');//3、发送xhr.send()//4、事件绑定 处理服务端返回的结果// on when 当...时候//readystate 是 xhr 对象中的属性,表示状态 0 1 2 3 4//change 改变xhr.onreadystatechange = function(){//判断(=4 服务端返回了所有的结果)if(xhr.readyState === 4){//判断响应状态码 200 404 403 401 500// 2xx 成功if(xhr.status >= 200 && xhr.status<300){//处理结果 行 头 空行 体//1、响应行console.log(xhr.status)//状态码 200console.log(xhr.statusText)//状态字符串 OKconsole.log(xhr.getAllResponseHeaders())//所有响应头 content-length: 10 content-type: text/html; charset=utf-8console.log(xhr.response)//响应体 hello ajaxresult.innerHTML = xhr.response;}else{}}}}</script>
js//1、引入expressconst express = require('express')//2、创建应用对象const app = express()//3、创建路由规则//request是对请求报文的封装//response是对响应报文的封装app.get('/server',(request,response)=>{//设置响应头 设置允许跨域response.setHeader('Access-Control-Allow-Origin','*')//设置响应体response.send('hello ajax')})//4、监听端口启动服务app.listen(8000,()=>{console.log("服务已经启动,8000端口监听中...")})
3-2 Ajax设置请求参数
在url后 缀参数

