AJAX 课程学习笔记三

简介: AJAX 课程学习笔记三

七、jQuery发送Ajax请求

https://jquery.cuishifeng.cn/index.html

配置服务端server.js

// jQuery 服务
app.all('/jquery-server',(request,response)=>{
   
   
  // 设置响应头  设置允许跨域
  response.setHeader('Access-Control-Allow-Origin','*');
  const data={
   
   name:'Mark'};
  response.send(JSON.stringify(data));

});
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>jQuery发送AJAX请求</title>
  <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
  <link rel="stylesheet" crossorigin="anonymous" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">

  <!-- 最新的 Bootstrap 核心 JavaScript 文件 -->
  <script crossorigin="anonymous" src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>
  <script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
</head>
<body>
  <div class="container">
    <h2 class="page-header">jQuery发送Ajax请求</h2>
    <button class="btn btn-primary">GET</button>
    <button class="btn btn-danger">POST</button>
    <button class="btn btn-info">通用型方法ajax</button>
  </div>
  <script>
    $('button').eq(0).click(function (){
   
   
      $.get('http://127.0.0.1:8000/jquery-server',{
   
   a:200,b:400},function (data){
   
   
        console.log(data)
      },'json')
    });
    $('button').eq(1).click(function (){
   
   
      $.post('http://127.0.0.1:8000/jquery-server',{
   
   a:200,b:400},function (data){
   
   
        console.log(data)
      })
    });
    $('button').eq(2).click(function (){
   
   
      $.ajax({
   
   
       // url
       url:'http://127.0.0.1:8000/jquery-server',
       // 参数
       data:{
   
   a:100,b:200},
      //  请求类型
        type:'GET',
      //  设置响应体结果类型
        dataType:'json',
      //  成功的回调
        success:function (data){
   
   
          console.log(data);
        },
      //  超时时间
        timeout:2000,
      //  失败的回调
        error:function (){
   
   
          console.log('出错了!');
        }
      })
    })
  </script>
</body>
</html>

八、axios

https://blog.csdn.net/qq_53810245/article/details/121320950
官网:http://axios-js.com/zh-cn/docs/index.html
在这里插入图片描述
在这里插入图片描述

btn[2].onclick = function (){
   
   
    axios({
   
   
    //  请求方法
      methods:'POST',
    //  url
      url:'/axios-server',
      // URL参数
      params:{
   
   
        vip:1,
        level: 30
      },
    //  头信息
      headers:{
   
   
        a:100,
        b:120
    },
    //  请求体的参数
      data:{
   
   
        username:'admin',
        password:'admin'
      }
    }).then(response =>{
   
   
      console.log(response);
    })
  }

九、使用fetch函数发送AJAX请求

官网https://developer.mozilla.org/zh-CN/docs/Web/API/fetch
在这里插入图片描述

十、跨域

违背同源策略的就算跨域

1、同源策略

同源策略(Same-Origin Policy)最早是由 Netscape 公司提出,是浏览器的一种安全策略。

  • 同源:协议、域名、端口号 必须完全相同
  • 违背同源策略的就算跨域

2、如何解决跨域

2.1、JSONP

  • JSONP(JSON with Padding),是一个非官方的跨域解决方案,只支持get请求
  • 在网页有一些标签天生具有跨域能力,比如:imglinkiframescript
  • JSONP就是利用script标签的跨域能力来发送请求的

    2.2 JSONP 的使用

  1. 动态创建一个script标签 var script = document.createElement("script");
  2. 设置script的src,设置回调函数
    script.src = "http://localhost:3000/testAJAX?callback=abc"

server.js

const express = require('express')
const {
   
   request, response} = require("express");
// const {request, response} = require("express");
const app = express();
app.get('/home',(request,response)=>{
   
   
  // 响应一个页面
  response.sendFile(__dirname + '/index.html')
});

app.all('/data',(request,response)=>{
   
   
  response.send('用户数据');
});

//jsonp 服务
app.all('/jsonp-server',(request,response)=>{
   
   
  const data = {
   
   
    name : '尚硅谷atguigu'
  };
  // 将数据转化为字符串
  let str = JSON.stringify(data);
  // 返回结果
  response.end(`handle(${
     
     str})`);
});
app.listen(9000,()=>{
   
   
  console.log('9000端口服务已启动...');
});

demo.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>JSON原理演示AJAX</title>
  <style>
    #result{
    
    
        width: 300px;
        height: 200px;
        border: solid 1px #78a;
    }
  </style>
</head>
<body>
<div id="result"></div>
<script>
  // 处理数据
  function handle(data){
    
    
//  获取result元素
    const result = document.getElementById('result');
    result.innerHTML = data.name;
  }
</script>
<script src="http://127.0.0.1:9000/jsonp-server"></script>

</body>
</html>

3、CORS

3.1、CORS是什么

CORS是跨域资源共享。是官方 的跨域解决发方案,她的特点是不需要在客户端做任何特殊的操作,完全在服务器中进行处理,支持get和post请求。跨域资源共享标准新增了一组HTTP首部字段,允许服务器声明哪些源站通过浏览器有权限访问哪些资源

3.2、CORS怎么工作的?

CORS是通过设置一个响应头来告诉浏览器,该请求允许跨域,浏览器收到该响应以后就会对响应放行

3.3、CORS的使用

主要是服务器端的设置:

const express = require('express')
const {
   
   request, response} = require("express");
// const {request, response} = require("express");
const app = express();

// CORS
app.all('cors-server',(request,response)=>{
   
   
  // 设置响应头, * 代表支持所有all
  response.setHeader("Access-Control-Allow-Origin","*")
  // 设置请求的头
  response.setHeader("Access-Control-Allow-Headers","*")
  // 设置请求的方法
  response.setHeader("Access-Control-Allow-Methods","*")
  response.send('HELLO CORS')
});

app.listen(9000,()=>{
   
   
  console.log('9000端口服务已启动...');
});

demo.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>CORS</title>
  <style>
    #result{
    
    
        width: 300px;
        height: 200px;
        border: solid 1px #f89;
    }
  </style>
</head>
<body>
  <button>发送请求</button>
  <div id="result"></div>
  <script>
    const btn = document.querySelector('button');
    btn.onclick = function (){
    
    
      // 1、创建对象
      const x = new XMLHttpRequest();
      // 2、初始化设置
      x.open('get','http://127.0.0.1:9000/cors-server')
    //3、发送
      x.send()
    //  4、绑定事件
      x.onreadystatechange = function (){
    
    
        if (x.readyState === 4){
    
    
          if (x.status >=200 && x.status<300){
    
    
            // 输出响应体
            console.log(x.response)
          }
        }
      }
    }
  </script>
</body>
</html>
相关文章
|
2月前
|
JSON 缓存 前端开发
AJAX 课程学习笔记二
AJAX 课程学习笔记二
|
2月前
|
XML 前端开发 JavaScript
AJAX 课程学习笔记一
AJAX 课程学习笔记一
|
4月前
|
JSON 前端开发 JavaScript
前端知识笔记(三十七)———Django与Ajax
前端知识笔记(三十七)———Django与Ajax
27 0
|
4月前
|
XML JSON 前端开发
Ajax后端极简笔记
Ajax后端极简笔记
50 0
|
4月前
|
JSON 前端开发 JavaScript
前端知识笔记(二)———Django与Ajax
前端知识笔记(二)———Django与Ajax
28 0
|
8月前
|
前端开发
前端学习笔记202306学习笔记第四十三天-ajax的经典四大步骤3
前端学习笔记202306学习笔记第四十三天-ajax的经典四大步骤3
50 0
|
8月前
|
前端开发
前端学习笔记202306学习笔记第四十三天-ajax的经典四大步骤1
前端学习笔记202306学习笔记第四十三天-ajax的经典四大步骤1
42 0
|
5月前
|
XML 前端开发 JavaScript
什么是Ajax和jquery
什么是Ajax和jquery
39 0
|
4月前
|
JSON 前端开发 Java
利用Spring Boot处理JSON数据实战(包括jQuery,html,ajax)附源码 超详细
利用Spring Boot处理JSON数据实战(包括jQuery,html,ajax)附源码 超详细
60 0
|
4月前
|
敏捷开发 JavaScript 前端开发
❤❤❤【Vue.js最新版】sd.js基于jQuery Ajax最新原生完整版for凯哥API版本❤❤❤
❤❤❤【Vue.js最新版】sd.js基于jQuery Ajax最新原生完整版for凯哥API版本❤❤❤