服务器|Ajax跨域与封装

Ajax 6.跨域 6.1 同源策略

  • 同源策略(Same-Origin Policy)最早由Netscape 公司提出,是浏览器的一种安全策略
  • 同源: 协议、域名、端口号必须完全相同
  • 跨域: 违背同源策略就是跨域
6.2 如何解决跨域 6.2.1JSONP
jsonp 只支持get请求不支持post请求
  1. JSONP 是什么
【服务器|Ajax跨域与封装】JSONP(JSON with Padding),是一个非官方的跨域解决方案,纯粹凭借程序员的聪明
才智开发出来,只支持get 请求。
  1. JSONP 怎么工作的?
在网页有一些标签天生具有跨域能力,比如:img link iframe script。
JSONP 就是利用script 标签的跨域能力来发送请求的。
  1. JSONP 的使用
html代码
//1. 创建 script 标签 const script = document.createElement('script'); //2. 设置标签的 src 属性 script.src = 'http://127.0.0.1:8000/check-username?callback=abc'; //3. 将script 添加到body 中 document.body.appendChild(script); function abc(data) { alert(data.name); };

后端代码
app.get("/check-username" , function (req , res) { var callback = req.query.callback; const data = https://www.it610.com/article/{ name:'孙悟空' }; //将数据转化为字符串 let str = JSON.stringify(data); //返回结果(一段可执行的JavaScript代码) response.end(`${callback}(${str})`); });

6.2.2 完整JSONP代码
JSONP > function fn(date){ console.log('xjszsd'); console.log(date); } > var btn = document.getElementById('btn'); btn.onclick=function(){ // 创建script标签 var script = document.createElement('script'); // 添加src属性 script.src='http://localhost:3000/jsonp?callback=fn'; // 将script标签追加到页面中 document.body.appendChild(script); //加载完删除script标签 script.onload=function(){ // 删除子节点 document.body.removeChild(script); } }// 封装jsonp function jsonp(options){ // 创建script标签 var script = document.createElement('script'); // 添加src属性 script.src=https://www.it610.com/article/options.url; // 将script标签追加到页面中 document.body.appendChild(script); //加载完删除script标签 script.onload=function(){ // 删除子节点 document.body.removeChild(script); } }

6.3 CORS https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS
CORS 是什么?
CORS(Cross-Origin Resource Sharing),跨域资源共享。CORS 是官方的跨域解决方
案,它的特点是不需要在客户端做任何特殊的操作,完全在服务器中进行处理,支持
get 和post 请求。跨域资源共享标准新增了一组HTTP 首部字段,允许服务器声明哪些
源站通过浏览器有权限访问哪些资源
CORS 怎么工作的?
CORS 是通过设置一个响应头来告诉浏览器,该请求允许跨域,浏览器收到该响应
以后就会对响应放行。
CORS 的使用
主要是服务器端的设置:
router.get("/testAJAX" , function (req , res) { //通过res 来设置响应头,来允许跨域请求 //res.set("Access-Control-Allow-Origin","http://127.0.0.1:3000"); res.set("Access-Control-Allow-Origin","*"); //允许所有来源访问 res.send("testAJAX 返回的响应"); });

常见问题解决 IE缓存问题
问题:在一些浏览器中(IE),由于缓存机制的存在,ajax 只会发送的第一次请求,剩 余多次请求不会在发送给浏览器而是直接加载缓存中的数据。
解决方式:浏览器的缓存是根据 url 地址来记录的,所以我们只需要修改 url 地址 即可避免缓存问题。
xhr.open("get","/testAJAX?t="+Date.now());

ajax允许携带cookie访问要设置:withCredential=true
JQuery封装的ajax: 代码示意:
src="http://img.readke.com/220825/212A05636-1.jpg"> Jquery中ajax > $('#btn').on('click',function(){ $.ajax({ // 请求方式 type:'post', // 请求地址 url:'http://localhost:3000/post', // 请求参数 data:JSON.stringify({ name:'xjszsd', age:20 }), // 在请求发送之前 beforeSend:function(){ alert('xjszsd'); // 请求不会被发送 // return false; }, // 请求参数类型 contentType:'application/json', // 成功回调函数 success:function(response){ // 方法内部会自动将json字符串转化为json对象 console.log(response); }, // 失败回调函数 error:function(xhr){ console.log(xhr); } }) })

serialize() 方法
将表单中的数据自动拼接成为字符串类型的参数
var params = $('#form').serialize();

示例:
src="http://img.readke.com/220825/212A05636-1.jpg"> serialize方法
> $('#form').on('submit',function(){var params = $('#form').serialize(); // 将form表单参数转换为参数数组 var totals = $(this).serializeArray(); console.log(totals); // 循环,将参数数组转换为对象 var result = {}; $.each(totals,function(index,value){ result[value.name]=value.value; console.log(index); console.log(value); }); console.log(result); console.log(params); $.ajax({ // 请求方式 type:'post', // 请求地址 url:'http://localhost:3000/post', data:JSON.stringify(result), // 在请求发送之前 beforeSend:function(){ alert('xjszsd'); // 请求不会被发送 // return false; }, // 请求参数类型 contentType:'application/json', // 成功回调函数 success:function(response){ // 方法内部会自动将json字符串转化为json对象 console.log(response); }, // 失败回调函数 error:function(xhr){ console.log(xhr); } }) return false; });

. g e t ( ) 、 .get()、 .get()、.post()方法
作用: . g e t ( ) 方法用于发送 g e t 请求, .get()方法用于发送get请求, .get()方法用于发送get请求,post方法用于发送post请求
$.get('url',{name:'xjszsd',age=20},function(response){}) $.post('url',{name:'xjszsd',age=20},function(response){})

    推荐阅读