Ajax的应用场景

1.页面上拉加载更多数据
2.列表数据无刷新分页
3.表单项离开焦点数据验证
4.搜索框提示文字下拉列表

Ajax的运行环境

Ajax技术需要运行在网站环境中才能生效,当前课程会使用Node创建的服务器作为网站服务器。
ajax
Web数据交互方式
实现了客户端与服务端之间的数据交互
我们使用js里边的ajax来实现前后台的数据交互
特点: 异步数据请求
体积小 请求速度快 加载速度
原理:
前台使用js调用原生ajax请求 调用后台接口对后台发起数据请求(Get/Post) 后台获取到前台发起的请求
使用对应的mysql数据库语句对数据库进行增删改查操作 将得到的数据库数据返回给前台页面 前台拿到数据进行页面渲染

  1. //原生ajax
  2. var xhr=new XMLHttpRequest()
  3. xhr.onreadystatechange=function() {
  4. if(xhr.readyState==4 && xhr.status==200) {
  5. var data=xhr.responseText; // 后台接口返回的后台数据
  6. }
  7. }
  8. xhr.open("get", url, true) // true表示异步请求 false表示同步请求
  9. xhr.send()
  1. var xhr=new XMLHttpRequest()
  2. var str=""
  3. var ul=document.querySelector("ul")
  4. var reg=/(w.h){1,}/
  5. xhr.onreadystatechange=function() {
  6. if(xhr.readyState==4 && xhr.status==200) {
  7. var res=JSON.parse(xhr.responseText); // 后台接口返回的后台数据
  8. console.log(res.data.hot)
  9. for(var i=0; i<res.data.hot.length; i++) {
  10. str+=`
  11. <li>
  12. <img src="${res.data.hot[i].img.replace(reg, '128.180')}" alt="">
  13. <div class="text">
  14. <p class="title">${res.data.hot[i].nm}</p>
  15. <p class="rating">观众评<span>${res.data.hot[i].sc}<span></p>
  16. <p class="players">主演: ${res.data.hot[i].star}</p>
  17. </div>
  18. </li>
  19. `
  20. }
  21. ul.innerHTML=str
  22. }
  23. }
  24. xhr.open("get", "https://i.maoyan.com/api/mmdb/movie/v3/list/hot.json?ct=荥阳&ci=557&channelId=4", true) // true表示异步请求 false表示同步请求
  25. xhr.send()

跨域

产生原因 1 同端口 www.demo.com:8080 // 8080端口号
2 同域名 www.demo.com/index.html www.demo.com/detail 接口
3 同协议 https http
以上三个条件有任何不满足就会产生跨域
请求接口的网页 例如 https://www.test.com:3000/mine.html
被请求接口 例如 https://www.test.com:3000/list
解决跨域办法 1 客户端(前端)
1 传统的解决跨域使用jsonp
2 nginx反向代理
3 proxy域名代理
如果没有上线 在本地进行项目测试时候 想要解决跨域
我们可以使用浏览器自带插件
你也可以使用nginx在本地进行配置
在谷歌浏览器属性中 目标位置添加 后缀 在末尾添加 —disable-web-security —user-data-dir=C:\MyChromeDevUserData
2 服务端(后台)
只需要给后台代码添加一个header头文件就可以处理

image.png

image.png
image.png

jquery ajax

jquery ajax常用的三种方式
$.ajax() 既可以post get delete put
格式:
$.ajax({
url: “请求的接口地址”,
type: “请求接口的方式post get put delete”,
data: {
后台要求传递的参数
},
success: function(res) {
// res就是后台给你返回的数据
},
fail: function(err) {
// err就是请求失败后台返回的数据
}
})
$.get() // 只适用于get请求
格式:
$.get(url, data, function() {}, type)
一般情况下 我们只去用前三个参数
url表示请求的接口地址
data表示后台接口所需要的字段参数
function成功回调函数
type就是后台返回过来的数据类型格式 text html json等等
例如
$.get(“https://www.xxx.com”, {
参数名1: 参数值1,
参数名2: 参数值2

}, function(形参) {
console.log(形参) // 形参就表示后台返回的数据
}, “json”)
$.post() // 只适用于post请求
格式:
$.post(url, data, function() {}, type)
一般情况下 我们只去用前三个参数
url表示请求的接口地址
data表示后台接口所需要的字段参数
function成功回调函数
type就是后台返回过来的数据类型格式 text html json等等
例如
$.post(“https://www.xxx.com”, {
参数名1: 参数值1,
参数名2: 参数值2

}, function(形参) {
console.log(形参) // 形参就表示后台返回的数据
}, “json”)

原生ajax请求

原生ajax发起ajax请求
fetch promise异步回调 可以执行任意类型的请求post get
get请求 格式:
// get请求
fetch(“url”).then(function(response) {
return response.json() // 首先将后台的数据进行json格式化 然后在返回给浏览器
}).then(function(res) {
// console.log(res) 成功回调 返回后台数据
}).catch(function(err) {
console.log(err) 失败捕获 返回接口错误信息
})
post请求 格式:
fetch(“url”, {
method: “POST”,
headers: {
‘Content-Type’: ‘application/json’
},
body: JSON.stringfy({
// 请求的字段 发送给后台接口的
属性名1: 属性值1,
属性名2: 属性值2
})
}).then(function(response) {
return response.json() // 首先将后台的数据进行json格式化 然后在返回给浏览器
}).then(function(res) {
// console.log(res) 成功回调 返回后台数据
}).catch(function(err) {
console.log(err) 失败捕获 返回接口错误信息
})
  1. 原生js发起ajax请求
  2. fetch("https://cnodejs.org/api/v1/topics").then(function(response) {
  3. return response.json()
  4. }).then(function(res) {
  5. console.log(res)
  6. }).catch(function(err) {
  7. console.log(err)
  8. })
  1. var obj={
  2. admin: 'zhangsan',
  3. password: "123456"
  4. }
  5. $("button").click(function() {
  6. fetch("http://localhost:3000/register", {
  7. method: 'POST',
  8. headers: {
  9. 'Content-Type': 'application/json',
  10. },
  11. body: JSON.stringify(obj)
  12. }).then(response=> response.json()).then(res=> {
  13. console.log(res)
  14. })
  15. // $.post("http://localhost:3000/register", {
  16. // admin: "xcr007",
  17. // password: "124568"
  18. // },function(res) {
  19. // console.log(res)
  20. // })
  21. })
  1. $.get("https://cnodejs.org/api/v1/topics", {
  2. page: 1,
  3. limit: 50
  4. }, function(res) {
  5. console.log(res)
  6. for(var i=0; i<res.data.length; i++) {
  7. str+=`
  8. <li>${res.data[i].title}</li>
  9. `
  10. }
  11. $("ul").html(str)
  12. })
  1. $.ajax({
  2. url: "https://cnodejs.org/api/v1/topics",
  3. type: "GET",
  4. data: {
  5. page: 1,
  6. limit: 40
  7. },
  8. success: function(res) {
  9. console.log(res)
  10. for(var i=0; i<res.data.length; i++) {
  11. str+=`
  12. <li>${res.data[i].title}</li>
  13. `
  14. }
  15. $("ul").html(str)
  16. },
  17. fail: function(err) {
  18. console.log(err)
  19. }
  20. })

fetch请求

  1. <script>
  2. fetch("http://1ocalhost:3000/list").then(res => {
  3. return res.json()
  4. }).then(res1 => {
  5. console.log(res1)
  6. }).catch(err=>{
  7. console.log(err)
  8. })
  9. </script>

使用ajax请求接口渲染数据

  1. if(localStorage.getItem("user")) {
  2. var str=''
  3. fetch("http://localhost:3000/restaurant").then(function(res){
  4. return res.json()
  5. }).then(function(res1) {
  6. console.log(res1)
  7. for(var i=0; i<res1.data.length; i++) {
  8. str+=`
  9. <li>
  10. <img src="${res1.data[i].avatar}" alt="">
  11. <p>${res1.data[i].restaurant_name}</p>
  12. <p>${res1.data[i].address}</p>
  13. </li>
  14. `
  15. }
  16. document.querySelector("ul").innerHTML=str
  17. }).catch(function(err) {
  18. console.log(err)
  19. })
  20. }else {
  21. window.location.href="./login.html"
  22. }

ajax异步请求

post get put delete
post和get区别
1.使用Get请求时,参数在URL中显示,而使用Post方式,则不会显示出来
2.使用Get请求发送数据量小,Post请求发送数据量大
3.get请求需注意缓存问题,post请求不需担心这个问题
4.post传输数据乜有限制 get传输时候1kb
5.get比post传输更快 POST比GET更稳定也更可靠
例如:
进行网站注册登录操作时候 一般使用post
获取一些信息的时候 一般使用get请求
修改网站一些信息的时候 我们可以使用put
删除网站一些信息的时候 我们可以使用delete

AJAX-express框架

1.安装node.js //1.引入express
constexpress=require(‘express’);
// 2.创建应用对象
constapp=express();
// 3.创建路由规则
//request是对请求报文的封装
//response 是对响应报文的封装
app.get(‘/‘, (request, response) => {
//设置响应
response.send(‘HELLO EXPRESS’);
});
//4.监听端口启动服务
app.listen(8000, () => {
console.log(“服务已经启动,8000 端口监听中……”);
})
2.新建英文文件夹,vscode右键以管理员打开,右键在集成终端中打开
3.安装这个包,终端输入npm init —yes回车初始化
4.安装express框架,npm i express回车
5.
node demo.html 打印端口