服务器端存放5名学生的信息,在客户端用jQuery的ajax技术获取这5名学生的信息并用表格在页面中显示出来。学生信息如下:Student(id,name,html,css,nodejs)
学生信息使用类保存
客户端页面:
<!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>Document</title>
<!-- 导入jquery文件 -->
<script src="./jquery-3.4.1.js"></script>
</head>
<style>
table{border: 1px solid;}
td{width: 80px;border: 1px solid #666;text-align: center;border-collapse: collapse;}
</style>
<body>
<!-- 3、服务器端存放5名学生的信息,在客户端用jQuery的ajax技术获取这5名学生的信息并用表格在页面中显示出来。学生信息如下:
Student(id,name,html,css,nodejs) -->
<!-- 用户名:<input type="text" id="useName"> -->
<table id="table">
<thead>
<tr>
<td>学号</td>
<td>姓名</td>
<td>html</td>
<td>css</td>
<td>nodejs</td>
</tr>
</thead>
<tbody id="tbody"></tbody>
</table>
<script>
$(function(){//入口函数
// $(document).ready(()=>{//页面加载事件,页面加载时读取数据库中的数据
$.ajax({
url:'http://127.0.0.1:8090',
type:'get',//请求方式
dataType:'json',//服务器返回的数据格式
success:function(result){//回调函数,请求成功后服务器返回的数据:参数result中存放的是服务器返回的数据
for(let s of result){
$('#tbody').append(`<tr>
<td>${s.id}</td>
<td>${s.name}</td>
<td>${s.html}</td>
<td>${s.css}</td>
<td>${s.nodejs}</td>
</tr>`)
}
}
})
// })
})
</script>
</body>
</html>
学生类:
class Student{
constructor(id,name,html,css,nodejs){
this.id = id
this.name = name
this.html = html
this.css = css
this.nodejs = nodejs
}
show(){
console.log('学号:',this.id)
console.log('姓名:',this.name)
console.log('html成绩:',this.html)
console.log('css成绩:',this.css)
console.log('nodejs成绩:',this.nodejs)
}
}
module.exports = Student//导出类
web数据库:
const http = require('http')
const url = require('url')//对地址进行解析和转换
const Student = require('./student')//导入类
//1、创建服务器
const httpServer = http.createServer((req,res)=>{
//2、设置跨域
res.setHeader("Access-Control-Allow-Origin","*")//设置允许来自哪里的跨域访问,*:允许所有的跨域(不安全)
//设置允许跨域访问的方式:服务器接收哪些方式的跨域访问
res.setHeader("Access-Control-Allow-Methods","GET,PUT,POST,DELETE,OPTIONS")
//设置请求头中携带的参数
res.setHeader("Access-Control-Allow-Headers","Content-Type,request-origin")
//3、定义数组保存学生信息
let arr = [//学生信息
new Student(101,'张三',88,90,60),
new Student(102,'李四',80,77,78),
new Student(103,'王五',81,67,76),
new Student(104,'赵六',82,88,87),
new Student(105,'孙七',83,79,57)
]
if(req.url != './favicon.ico'){//取消浏览器的默认访问服务器
//4、设置响应信息的格式和字符集
res.setHeader('Content-Type','text/html;charset=utf8')
//5、将数组转换为JSON格式,发送给前端
let stuInfo = JSON.stringify(arr)
res.end(stuInfo)
}
})
//6、启动监听
httpServer.listen(8090,'127.0.0.1',()=>{
console.log('服务器已启动,运行在9000端口上')
})