jsonp为啥能跨域呢,我们来盗一下这个墓_html/css_WEB-ITnose
不知道大家最近看没看《鬼吹灯之寻龙诀 》,感觉IMAX-3D效果真不错,虽然剧情不咋滴,但是效果是出来了。好了,今天我们也来一场盗墓,这次是挖jsonp的坟,挖一挖为啥jsonp就能跨域呢,它咋就那么牛X呢。如果看到了这篇文章,那么大家对于跨域一定不陌生了,通俗说就是不同域请求资源。不过怎么就构成跨域呢,这个问题貌似在《白帽子讲web安全》这本书里讲的比较全面,本文不去深究了,我们今天是来盗墓的,开始干活。
基本思路
大家都知道<script>标签可以通过src来引入js文件,当然它可不是仅仅可以引入js文件,它能引入很多资源。比如看下方:</script>
这是新浪汽车首页引入了一个新浪汽车图库的php文件。如果你打开ip.php它返回如下信息(其实就是一段js代码,两个js方法get_city和get_ip_city):
如果你开发或者调试过跨域的接口,也就知道基本上jsonp和json就差一个callback参数,学名叫回调函数。这个回调函数就为我们定了穴,接下来我们从这里开始挖。
接口
为了方便大家测试,我就不单独写接口了,我们找一个现成的:
http://news.auto.sina.com.cn/m/label/get_label_info.php?label=%E8%BD%A6%E8%81%94%E7%BD%91&length=1&page=1&callback=callback
这个接口是支持跨域的,为啥呢,接下来我们开始挖。
测试跨域
如果接口支持跨域并且没有做其他限制,那么也就意味着这个接口在任何地方都可以调用。所以我们在本地新建一个test.html文件,文件内容如下:
<html><head><script src="http://news.auto.sina.com.cn/m/label/get_label_info.php?label=%E8%BD%A6%E8%81%94%E7%BD%91&length=2&page=1&callback=func"></script></head><body></body></html>
用chrome打开上述文件,然后右键审查元素,你将会收获一个错误信息,点击错误信息,可以得到如下图:
其实这个报错信息提示我们func未定义,其实就是我们传入的callback的参数未定义,那这个需要在哪里定义呢?当然是在我们的html页面中,我们在html中定义一下,代码如下:
<html><head><script>function func(data){ console.log(data);}</script><script src="http://news.auto.sina.com.cn/m/label/get_label_info.php?label=%E8%BD%A6%E8%81%94%E7%BD%91&length=2&page=1&callback=func"></script></head><body></body></html>
上述代码我们添加了一个func方法,这个方法接收一个参数,并且将传入的值打印到console中。在chrome中运行上述代码,并审查源代码,效果如下图:
这一次并没有报错,并且已经按照我们的预期将返回的值打印到了console中,其中的值其实就是json格式。
js的jsonp请求
这里我们用jQuery.ajax()方法去请求一下上述接口,来体验一下jsonp请求。当然你也可以用XMLHttpRequest/ActiveXObject,不过注意兼容性。代码如下:
<html><head><!-- 引入jquery包 --><script src="http://code.jquery.com/jquery-1.11.3.min.js"></script><script>$(function(){ $.ajax({ url: 'http://news.auto.sina.com.cn/m/label/get_label_info.php?label=%E8%BD%A6%E8%81%94%E7%BD%91&length=2&page=1', dataType:'jsonp', success:function(res){ console.log(res); } });});</script></head><body></body></html>
在chrome中打开上述文件,然后审查元素(记得要重新刷新页面哦),效果如下:
揭开谜底,发现宝藏
通过上边两种方式体验了一番,也许你已经知道了谜底。谜底就是js可以引入并运行跨域代码,而不能引入跨域的数据,jsonp通过回调函数来链接远程资源和本地js代码。回调函数在本地,而运行回调函数并传入参数是通过远程实现的。换句话说:jsonp返回来的是代码,而json返回来的是数据,浏览器为了安全起见不允许跨域请求数据,但是并没有限制不能运行远程代码。
那么如果你是一个后端开发人员,你写如下代码(PHP版本):
echo $callback."(".json_encode(['data']).")";
其实是相当于返回了一段调用js方法的代码,调用了js代码里的callback方法,而如果只是返回一串json,那么返回的是数据。如果你是js开发人员,需要注意jsonp返回的值是一段js代码,是有危险的,比如在callback前边加上一个while(1){}那你的代码就彻底歇菜了,不要轻易去使用别人的接口。此外还得提醒大家,jsonp只能通过GET方式传输,不能用POST等方式。
打完收工,今天我们从两个角度去思考了jsonp是怎么完成跨域的,其实本质是一样的,如果你想彻底弄明白这个过程,最好动手试一下。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

AnexampleofastartingtaginHTMLis,whichbeginsaparagraph.StartingtagsareessentialinHTMLastheyinitiateelements,definetheirtypes,andarecrucialforstructuringwebpagesandconstructingtheDOM.

GiteePages static website deployment failed: 404 error troubleshooting and resolution when using Gitee...

To achieve the effect of scattering and enlarging the surrounding images after clicking on the image, many web designs need to achieve an interactive effect: click on a certain image to make the surrounding...

The Y-axis position adaptive algorithm for web annotation function This article will explore how to implement annotation functions similar to Word documents, especially how to deal with the interval between annotations...

HTML, CSS and JavaScript are the three pillars of web development. 1. HTML defines the web page structure and uses tags such as, etc. 2. CSS controls the web page style, using selectors and attributes such as color, font-size, etc. 3. JavaScript realizes dynamic effects and interaction, through event monitoring and DOM operations.
