Ajax的相关

一 、先自己手写一个本地服务使用 node

  1. npm init --yes
  2. npm i express
  3. npm i nodemon -D
const express = require('express')
const app = new express()

app.all('/server',(request,response) => {
    // 设置响应头
    response.setHeader('Access-Control-Allow-Origin','*')
    response.setHeader('Access-Control-Allow-Headers','*')
    // 设置响应体
    response.send('hello world')
})

app.listen(3000,() => {
    console.log('监听成功' + new Date())
})

二、发送一个ajax请求

//get
document.addEventListener('click',()=>{
	let xhr = new XMLHttpRequest()
	xhr.open('get','http://127.0.0.1:3000/server?a=1&b=2&c=3')
	xhr.send()
	xhr.onload = function(){
		console.log(xhr.responseText)
	}
})
//post请求
document.querySelector('#btn_post').addEventListener('click',()=>{
		let xhr = new XMLHttpRequest()
		xhr.open('post','http://127.0.0.1:3000/server')
		xhr.send('123456') //参数
		xhr.onload = function(){
			console.log(xhr.responseText)
			 //在这里返回得到的就是服务端给的数据 hello world
		}
})

三、ie缓存问题

         document.addEventListener('click',()=>{
            let xhr = new XMLHttpRequest()
            xhr.open('get','http://127.0.0.1:3000/ie' + Date())
            xhr.send()
            xhr.onload = function(){
                console.log(xhr)
            }
            xhr.timeout = 2000 //设置延迟时间设置
            xhr.onerror = function (){
                // 当网络有问题的时候触发
            }
            xhr.ontimeout = function(){
                // 当超时的时候出发的函数
            }
        })
        /* 
ie缓存问题就是 假设当前页面用的服务器信息 更改了 ie浏览器会把之前缓存的数据展示出来
为了解决该方法 在后边加一个时间戳 这样每次出发就都是一个新的请求了
 */

设置类型

// 服务端代码
app.all('/json-server',(request,response) => {
    // 设置响应头
    response.setHeader('Access-Control-Allow-Origin','*')
    response.setHeader('Access-Control-Allow-Headers','*')
    // 设置响应体
    let data = {
        name:'孙策'
    }
    response.send(JSON.stringify(data))
})


//浏览器端
        document.addEventListener('keydown',()=>{
            let xhr = new XMLHttpRequest()
            xhr.open('get','http://127.0.0.1:3000/json-server')
            xhr.send()
            xhr.responseType = 'json'  //设置为json
//直接设置返回的类型为 json ,设置了之后,只需要在下边使用 
//xhr.response来获取内容就可以了
            //  就不用再设置 responseText 之类的类型了
            xhr.onload = function(){
                console.log(xhr.response)
            }
        })

Ajax与jQuery

// 服务端的路由代码
app.all('/jq_ajax',(request,response) => {
    response.setHeader('Access-Control-Allow-Origin','*')
    response.send(JSON.stringify({
        name:'孙策'
    }))
})


//客户端
<body>
    <button id="send">发送</button>
    <button id="ajax">ajax方法</button>
    <script>
    //单独的get发送
       $('button').eq(0).click(function(){
           $.get('http://127.0.0.1:3000/jq_ajax',
           {a:100,b:200},
           function(data){
                console.log(data)
           },'json')
       })
      //统一的写法
       $('button').eq(1).click(function(){
            $.ajax({
                url:'http://127.0.0.1:3000/jq_ajax',
                data:{a:100,b:200},  //参数
                type:'get',	//请求类型
                dataType:'json', //返回格式
                
                //成功时的回调
                success:function(data){
                    console.log(data)
                },
                timeout : 2000, // 限制时间
                
                // 失败的回调
                error:function(){
                    console.log('chucuo')
                }
            })
       })
    </script>
</body>

同源策略:同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能,如果缺少了同源策略,则浏览器的正常功能可能都会受到影响。可以说Web是构建在同源策略基础之上的,浏览器只是针对同源策略的一种实现
所谓同源,指的是协议相同,域名相同,端口号相同才算是同一个源

jsonp的解决跨源

// jsonp的路由
app.all('/jsonp',(request,response) => {
    // 返回给前台的数据
    const data = {
        name:'孙策',
        age:17
    }
    let result = JSON.stringify(data)
    response.end(`handle(${result})`)
    //在上一步整个 end 里面都是浏览去去直接执行的代码,
    //浏览器会把 `handle(${result})` 当作代码去执行
})


//客户端代码
        function handle(data){
            console.log(data) 
            //这里就会在控制台输出服务器返回的数据
        }
        
    </script>
    <script src="http://127.0.0.1:3000/jsonp"></script>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值