ajax专题(李强)02完结-jquery中发送ajax,axios发送ajax请求,fetch函数发送ajax请求,同源策略、jsonp的实现原理,jquery发送jsonp,设置cors响应头

1、jquery中如何发送ajax请求

发送get请求

$('#send').click(function(){
    $.get('http://localhost:3000/test',{name:'zhangsan',age:34},function (data) {
      console.log(data)
    })
  })

发送post请求

$('#send').click(function(){
    $.post('http://localhost:3000/test',{name:'zhangsan',age:34},function (data) {
      console.log(data)
    })
  })

响应json类型数据

 $('#send').click(function(){
    $.post('http://localhost:3000/test',{name:'zhangsan',age:34},function (data) {
      console.log(data)
    },'json')
    $.get('http://localhost:3000/test',{name:'zhangsan',age:34},function (data) {
      console.log(data)
    },'json')
  })
2、jquery通用发送ajax请求
<script>

  $('#send').click(function(){
    $.post('http://localhost:3000/test',{name:'zhangsan',age:34},function (data) {
      console.log(data)
    },'json')
    $.ajax({
      url:'http://localhost:3000/test',
      type:'post',
      data:{
        name:'lisi',
        age:22,
        address:'hebei'
      },
      //响应体结果设置
      dataType:'json',
      success(msg){
        console.log(msg)
      },
      //超时时间
      timeout:2000,
      //失败的回到
      error(e){
        console.log(e)
      },
      //头信息设置
      header:{
        
      }

    })
  })


</script>
3、axios发送ajax请求

后面会专门学习axios专题
先要引入一个bootcdn

标签对中,或者其他标签前

  <script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js

axios是使用promise来处理响应回来的结果的

<script>
  const btn_get = document.querySelector('#send_get')
  const btn_post= document.querySelector('#send_post')
  const btn_ajax = document.querySelector('#send_ajax')
  //配置baseURL
  axios.defaults.baseURL='http://localhost:3000'

  //axios通用方式发送get请求
  btn_get.onclick = function () {
    //get请求
    axios.get('/axios', {
      //设置参数
      params: {
        id: 100,
        vip: 7
      },
      //设置请求头信息
      headers:{
        age:20
      }
    }).then((value) => {
      console.log(value)
    },(reason) =>{
      console.log(reason)
    } )
  }

  //axios通用方式发送post请求
  btn_post.onclick=function () {
      //get请求
      axios.post('/axios', {
        //设置参数
        params: {
          id: 200,
          vip: 9
        },
        //设置请求头信息
        headers:{
          name:'zhaoqian'
        },
        //设置请求体
        data:{
          username:'wangerxiao',
          age:33,
          address:'nanfang'
        }
      }).then((value) => {
        console.log(value)
      },(reason) =>{
        console.log(reason)
      } )

  }

  //axios通用方式发送ajax请求
  btn_ajax.onclick=function () {
    axios({
      method:'post',
      url:'axios',
      params:{
        vip:10,
        level:110
      },
      //头信息
      headers:{
        province:'henan'
      },
      //请求体参数
      data:{
        username:'lisiguang',
        age:22
      }
    }).then(respone=>{
      console.log(respone)
      console.log(respone.status)
      console.log(respone.statusText)
      //响应头信息
      console.log(respone.headers)
      //响应体
      console.log(respone.data)
    })
  }


</script>

4、fetch函数发送ajax请求(使用很少)

也是用promise来处理响应结果

<script>
  const send_fetch = document.querySelector('#send_fetch')

  //axios通用方式发送get请求
  send_fetch.onclick = function () {
    fetch('http://localhost:3000/fetch',{
      method:'post',
      //请求头
      headers:{
        name:'haige',
        age:55
      },
      //请求体
      body:'username=zhangsan&passwrod=1234'
    }).then(response=>{
      return response.json()
    }).then(response=>{
      console.log(response.data.name)
    })

  }


</script>
5、同源策略

协议,域名,端口必须一致
违背同源就是跨域
ajax默认同源策略
后端代码的几个问题

router.get('/home', function(req, res, next) {
  //res.send('这里是users/home页面');
  let path=require('path')
  //先获取当前路径的父级
  let newpath=path.resolve(__dirname,'..')
  //指定参数的根,sendFile需要一个绝对路径,可以通过{root:path}的方式来获得任意根目录
  res.sendFile('/test01.html',{ root: newpath+'/public' })
});

如何获得__dirname的父级目录可以使用

  let path=require('path')

参考如下文章
https://blog.csdn.net/MyNameIsXiaoLai/article/details/85288873
对于readFile指定新路径可以使用

res.sendFile('/test01.html',{ root: newpath+'/public' })

参考文章在:
http://www.mianshigee.com/question/117839vdq

6、jsonp的实现原理

但我觉得只用jsonp来解决跨域问题太弱了,至少还有其他三种方法解决跨域问题
实际上跨域还可以使用jsonp,cros,代理服务,中间层转发
只能实现get请求

<script>标签本身就是跨域的

看原理
1、服务器3000,
目录结构:
在这里插入图片描述
2、public/javascripts/jsonp_data.js

const data={
  name:'zhangsan',
  age:33,
  address:'beijing'
}

handle(data)

2、服务器3001,
目录结构:
在这里插入图片描述
2、public/jsonp.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>3001</title>
  <style type="text/css">
    #result{ width: 200px; height: 200px; border:1px solid gray}
  </style>
</head>
<body>
<div id="result"></div>
<script>
  function handle(data){
    const result=document.querySelector('#result')
    console.log(data.name)
    result.innerHTML=data.name
  }
</script>
<script src="http://localhost:3000/javascripts/jsonp_data.js"></script>

</body>
</html>

现在从3001上访问jsonp.html,但是data和函数的执行都在3000上

在这里插入图片描述
另一例
1、3000服务器上添加路由

//jsonp服务
router.all('/jsonp',(req,res,next)=>{
  res.send('console.log("从3000服务器上jsonp上获得的响应")')
})

2、30001服务器上的public/jsonp.html

<script src="http://localhost:3000/users/jsonp"></script>

结果:
成功返回结果
3001服务器还可以这么写

router.all('/jsonp',(req,res,next)=>{
  const data={
    name:'lisi'
  }
  let str=JSON.stringify(data)
  //让客户端执行返回的模板字符串,同时还执行了handle函数
  res.end(`handle(${str})`)
})
7、原生jsonp实现原理

实际上就是在页面生成一个script标签,设置script的src属性是另外一个源就行。
1、3000服务器上的路由

//jsonp服务2
router.all('/jsonp_original',(req,res,next)=>{
  const data={
    exist:1,
    msg:'用户已存在'
  }
  let str=JSON.stringify(data)
  //让客户端执行返回的模板字符串,同时还执行了handle函数
  res.end(`handle(${str})`)
})

2、3001服务器上的jsonp.html页面

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>3001</title>
  <style type="text/css">
    #result{ width: 200px; height: 200px; border:1px solid gray}
  </style>
</head>
<body>
<div>
  <input type="text" id="myinput"/>
  <p id="show"></p>
</div>
<script>

 const myinput=document.querySelector('#myinput')
 const show=document.querySelector('#show')

 function handle (data) {
   myinput.style.border='1px solid #f00'
   //修改p的提示文本
   show.innerHTML=data.msg
 }
  myinput.onblur=function(){
   //获取输入框的文本
   let username=this.value
    //向服务器发送请求,监测用户名是否存在
    //创建一个script标签
    const script=document.createElement('script')
    //设置script对的src地址
    script.src='http://localhost:3000/users/jsonp_original'
    //将script插入到文档中
    document.body.appendChild(script)
  }
</script>

</body>
</html>

结果:
活动区到了相应响应信息

8、jquery发送jsonp

发送jsonp请求的时候,jquery会自动生成一个函数作为参数传送到服务器端。参数以t url='http://localhost:3000/users/jsonp_jquery?callback=?'的形式传递
f服务器接收到该函数后,用模板字符串解析后响应给客户端。
1、3000服务器路由

//jquery-json
router.all('/jsonp_jquery',(req,res,next)=>{
  const data={
    name:'wangxiaoer',
    address:['beijing','shanghai','shenzhen']
  }
  let str=JSON.stringify(data)
  //接收客户端传过来的callback函数
  let callback=req.query.callback


  //让客户端执行返回的模板字符串,同时还执行了handle函数
  res.end(`${callback}(${str})`)
})

2、3001服务器上的jsonp.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>3001</title>
  <style type="text/css">
    #result{ width: 200px; height: 200px; border:1px solid gray}
  </style>
  <script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js
"></script>
</head>
<body>
<div>
  <button id="send_jsonp">发送jsonp请求</button>
  <div id="result"></div>
</div>
<script>

  $('#send_jsonp').click(function(){
    //后面要加?callback=?,实际上是传了个callback函数过去
    let url='http://localhost:3000/users/jsonp_jquery?callback=?'
    $.getJSON(url,function(data){
      $('#result').html(`
      名称:${data.name},
      地址:${data.address}
      `)
    })
  })

</script>

</body>
</html>
9、设置cors响应头
  • cors就是跨域资源共享,不需要在客户端做任何特殊的操作,完全在服务器中进行处理,支持get和post请求
  • 跨域资源共享标准新增了一组http首部字段,允许服务器你声明哪些源站通过浏览器有权限访问哪些资源。
  • cors通过设置一个响应头来告诉浏览器,该请求允许跨域,浏览请收到该响应后,就会对响应放行
  • 主要是服务器端的设置

1、3000服务器端代码

//cors
router.all('/cors',(req,res,next)=>{
  //设置同源的响应头
  //允许所有页面都可以跨域访问
  res.setHeader('Access-Control-Allow-Origin','*')
  //允许所有3001服务器可以跨域访问
  res.setHeader('Access-Control-Allow-Origin','http://localhost:3001')

  res.send('hello cors')
})

2、3001客户端代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>3001</title>
  <style type="text/css">
    #result{ width: 200px; height: 200px; border:1px solid gray}
  </style>
  <script crossorigin="anonymous" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js
"></script>
</head>
<body>
<div>
  <button id="send_btn">发送jsonp请求</button>
  <div id="result"></div>
</div>
<script>
  const send_btn=document.querySelector('#send_btn')
  const result=document.querySelector('#result')

  send_btn.addEventListener('click',function(){
    const xhr=new XMLHttpRequest()
    xhr.open('get','http://localhost:3000/users/cors')
    xhr.send()

    xhr.onreadystatechange=function(data){
      if (xhr.readyState===4){
        if (xhr.status>=200 && xhr.status<300){
          console.log(xhr.response)
          result.innerHTML=xhr.response
        }
      }
    }
  })

</script>

</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值