当前位置:网站首页>利用Jsonp跨域请求数据
利用Jsonp跨域请求数据
2022-06-29 06:38:00 【Yuan_mingyu】
前言 :本文示例部署在XAMPP建站集成软件包上,在localhost环境下进行测试
1、什么是跨域
由于浏览器同源策略,凡是发送请求url的协议、域名、端口三者之间任意一与当前页面地址不同即为跨域。存在跨域的情况 :
(1)网络协议不同,如http协议访问https协议。
(2)端口不同,如8080端口访问3000端口。
(3)域名不同,如aaaa.com访问bbbb.com。
(4)子域名不同,如java.ddd.com访问qianduan.ddd.com。
(5)域名和域名对应ip,如www.a.com访问20.205.28.90.
2、Jsonp方法
因为srript标签是不存在跨域的,所以利用 script标签,加载src路径,实现跨域加载js文件。该js文件中需要定义好一个方法,将该方法名传递给服务端,服务端根据该方法名,拼装一个方法调用语句,响应给浏览器。又浏览器来执行该语句调用方法。通过参数,将响应的数据取出即可。
(1)原生JS请求方式
前端代码:
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = './js/text.js';
document.head.appendChild(script);
// 回调执行函数
function onBack(res) {
console.log(res) //{name:"小明",age:24}
}
后端代码:
onBack({
name:"小明",
age:24
})
这里需要注意的是,后端的数据形式必须作为函数的参数,且函数名要前后端保持一致。
(2)Jquery中的ajax请求方式
前端代码:
$.ajax({
url:"./js/text.js",
type:"GET",
dataType:"jsonp", // 定义返回方式为jsonp
jsonpCallback:"onBack", //定义回调函数名字,前后端保持一致
success:function(data){
console.log(data) //{name:"小明",age:24}
},
error:function(res){
console.log("请求失败!")
}
})
后端代码:
onBack({
name:"小明",
age:24
})
- 缺点1:只能使用get请求。
- 缺点2:因为使用的是script标签,存在安全隐患。
- 优点 :支持老式浏览器,以及可以向不支持CORS的网站请求数据。
原文:https://blog.csdn.net/weixin_43948229/article/details/86528111
边栏推荐
猜你喜欢

CI工具Jenkins安装配置教程

Creating a new generation of production and service tools with robot education

Exploring the depth of objects in JVM series

QT serial port programming

What are the conditions for a high-quality public chain?

YGG cooperated with Web3 platform leader to empower the creative community with Dao tools and resources

Redis of NoSQL database (I): Installation & Introduction

Baidu applet automatically submits search

多模态 —— Learnable pooling with Context Gating for video classification

Error: GPG check FAILED Once install MySQL
随机推荐
JVM系列之对象深度探秘
Mongostat performance analysis
[translation] [Chapter II ①] mindshare PCI Express technology 3.0
Exclusive download. Alibaba cloud native brings 10+ technical experts to bring new possibilities of cloud native and cloud future
Daily question 1 - force deduction - there are three consecutive arrays of odd numbers
Object detection - VIDEO reasoning using yolov6
Spark RDD案例:统计每日新增用户
Service grid ASM year end summary: how do end users use the service grid?
QT STL type iterator
NoSQL数据库之Redis(四):Redis新数据类型
WordPress adds article topping, password protection, and privacy Tags
jetson tx2
How to do the performance pressure test of "Health Code"
try anbox (by quqi99)
Qt QFileInfo简介
期末总结——Spark
Message queue batch processing refund order through queue
Save token get token refresh token send header header
【软件测试】接口——基本测试流程
关于端口转发程序的一点思考