Home > Web Front-end > JS Tutorial > body text

Completely master the principles and implementation of jsonp

小云云
Release: 2018-01-18 09:32:06
Original
1658 people have browsed it

Regarding cross-domain issues, this article mainly gives you a detailed analysis of the principles of jsonp, a detailed analysis of the principles of jsonp and a summary of cross-domain issues with pictures and texts. Hope it can help you.

Detailed analysis of the principles and implementation methods of jsonp

1: Cross-domain issues.

Second, the reason why cross-domain occurs

Js cannot make cross-domain requests. For security reasons, js cannot be cross-domain when designed.

What is cross-domain:

1. When the domain names are different.

2. The domain names are the same but the ports are different.

Only when the domain name is the same and the port is the same, access is possible.

You can use jsonp to solve cross-domain problems.

3. Cross-domain failure case 3.1, same-origin policy

First of all, for security reasons, browsers have a same-origin policy mechanism. The same-origin policy prevents loading from one source. Document or script Gets or sets properties of a document loaded from another source. It seems that I don’t know what it means, but you will know it after you practice it.

3.2, just create two web pages

One port is 2698 and the other is 2701. By definition, they are from different sources.

3.3. Use jQuery to initiate requests from different sources.

Add a button on the webpage with port 2698. The Click event will initiate two random requests to port 2701. domain request.

$("#getOtherDomainThings").click(function () {
$.get("http://localhost:2701/Scripts/jquery-1.4.4.min.js", function (data) {
console.log(data)
})

$.get("http://localhost:2701/home/index", function (data) {
console.log(data)
})
})
Copy after login

According to the same-origin policy, it will obviously be tragic. The browser will block and not initiate the request at all. (not allowed by Access-Control-Allow-Origin)

OK, it turns out that jsonp is to solve this problem.

In other words, the json data of another project is directly requested in a src or a url.

For example, in the URL of the page in the project with port 8080, the statement http://localhost:8081/category.json is directly requested, and this category.json is in the directory of the 8081 webapp. Next, a cross-domain request prompt will be generated.

Four, cross-domain solution 4.1, inspiration

We sometimes often see such code in projects

<script type="text/javascript" src="https://com/seashell/weixin/js/jquery.js"></script>
Copy after login

So even if they are not in the same project, You can also request success. This loophole, or technology, is used to achieve generous requests.

4.2, Method (Case 1) 4.2.1, Use script to obtain json from different sources

Since it is called jsonp, it is obvious that the purpose is still json, and it is obtained across domains. Based on the above analysis, it is easy to think of: use js to construct a script tag, assign the json url to the scr attribute of the script, insert the script into the dom, and let the browser obtain it. Practice:

function CreateScript(src) {
 $("<script><//script>").attr("src", src).appendTo("body")
}
Copy after login

Add a button event to test it:

$("#getOtherDomainJson").click(function () {
 $.get('http://localhost:2701/home/somejson', function (data) {
  console.log(data)
 })
})
Copy after login

##First, the first browser, http://localhost:2701/home The Url /somejson does exist as a json, and using the script tag to request the Url 2701 on the 2698 webpage is also 200OK, but a js syntax error is reported at the bottom. It turns out that after loading with the script tag, the response will be immediately executed as js. Obviously {"Email":"zhww@outlook.com","Remark":"I come from the far east"} is not a legal js statement.

4.2.2, Use script to obtain foreign jsonp

Obviously, putting the above json into a callback method is the easiest way. For example, it becomes like this:

If the jsonpcallback method exists, then jsonpcallback({"Email":"zhww@outlook.com","Remark":"I am from Far East"}) is a legal js statement.

What needs to be noted here is that the original json format data {"Email":"zhww@outlook.com","Remark":"I come from the far east"} must be encapsulated into jsonpcallback({ "Email":"zhww@outlook.com","Remark":"I'm from the Far East"}) Such a script can be parsed during the callback, otherwise the parsing will fail.

Since the server does not know what the client's callback is, it is impossible to hard code it into jsonpcallback, so it brings a QueryString to let the client tell the server what the callback method is. Of course, the key of QueryString must comply with the agreement of the server. , the one above is "callback".

Add callback function:

function jsonpcallback(json) {
 console.log(json)
}
Copy after login
Slightly change the parameters of the previous method:

$("#getJsonpByHand").click(function () {
 CreateScript("http://localhost:2701/home/somejsonp?callback=jsonpcallback")
})
Copy after login

##200OK, the server returns jsonpcallback({" Email":"zhww@outlook.com","Remark":"I'm from the Far East"}), we also wrote the jsonpcallback method, which will of course be executed. OK got json successfully. That's right, this is all about jsonp.

4.2.3, use jQuery to obtain jsonp

上面的方式中,又要插入script标签,又要定义一个回调,略显麻烦,利用jQuery可以直接得到想要的json数据,同样是上面的jsonp:

$("#getJsonpByJquery").click(function () {
$.ajax({
url: 'http://localhost:2701/home/somejsonp',
dataType: "jsonp",
jsonp: "callback",
success: function (data) {
console.log(data)
}
})
})
Copy after login

得到的结果跟上面类似。

4.2.4,总结

一句话就是利用script标签绕过同源策略,获得一个类似这样的数据,jsonpcallback是页面存在的回调方法,参数就是想得到的json。

jsonpcallback({"Email":"zhww@outlook.com","Remark":"我来自遥远的东方"})

4.3,案例二 4.3.1,简单应用

程序A中sample的部分代码:

<script type="text/javascript">
//回调函数
function callback(data) {
alert(data.message);
}
</script>
<script type="text/javascript" src="http://localhost:20002/test.js"></script>
Copy after login

程序B中test.js的代码:
1 //调用callback函数,并以json数据形式作为阐述传递,完成回调
2 callback({message:"success"});
这其实就是JSONP的简单实现模式,或者说是JSONP的原型:创建一个回调函数,然后在远程服务上调用这个函数并且将JSON 数据形式作为参数传递,完成回调。

将JSON数据填充进回调函数,这就是JSONP的JSON+Padding的含义吧。

一般情况下,我们希望这个script标签能够动态的调用,而不是像上面因为固定在html里面所以没等页面显示就执行了,很不灵活。我们可以通过javascript动态的创建script标签,这样我们就可以灵活调用远程服务了。

4.3.2,简单应用的升级以一

程序A中sample的部分代码:

<script type="text/javascript">
function callback(data) {
alert(data.message);
}
//添加<script>标签的方法
function addScriptTag(src){
var script = document.createElement('script');
script.setAttribute("type","text/javascript");
script.src = src;
document.body.appendChild(script);
}
window.onload = function(){
addScriptTag("http://localhost:20002/test.js");
}
</script>
Copy after login

程序B的test.js代码不变,我们再执行下程序,是不是和原来的一样呢。如果我们再想调用一个远程服务的话,只要添加addScriptTag方法,传入远程服务的src值就可以了。这里说明下为什么要将addScriptTag方法放入到window.onload的方法里,原因是addScriptTag方法中有句document.body.appendChild(script);,这个script标签是被添加到body里的,由于我们写的javascript代码是在head标签中,document.body还没有初始化完毕呢,所以我们要通过window.onload方法先初始化页面,这样才不会出错。

这样这个http://localhost:20002/test.js路径就可以动态的变化了。

4.3.3,简单应用的升级二

上面的例子是最简单的JSONP的实现模型,不过它还算不上一个真正的JSONP服务。我们来看一下真正的JSONP服务是怎么样的,比如Google的ajax搜索接口:http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=?&callback=?

q=?这个问号是表示你要搜索的内容,最重要的是第二个callback=?这个是正如其名表示回调函数的名称,也就是将你自己在客户端定义的回调函数的函数名传送给服务端,服务端则会返回以你定义的回调函数名的方法,将获取的json数据传入这个方法完成回调。有点罗嗦了,还是看看实现代码吧:

<script type="text/javascript">//添加<script>标签的方法function addScriptTag(src){ var script = document.createElement('script');script.setAttribute("type","text/javascript");script.src = src;document.body.appendChild(script);}window.onload = function(){//搜索apple,将自定义的回调函数名result传入callback参数中addScriptTag("http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=apple&callback=result");}//自定义的回调函数resultfunction result(data) {//我们就简单的获取apple搜索结果的第一条记录中url数据alert(data.responseData.results[0].unescapedUrl);}</script>
Copy after login

这个result方法是自己定义的,可能服务器上有千千万万个类似于result 的回调函数,但是我现在要的就是result而不是其它的方法,所以在这里自己定义回调方法。而不是写死的。可能下一次我就改成result1,result2,result3,等了只要自己把回调方法的名称改一下就行了。

4.4.4,jquery对jsonp的支持

jQuery框架也当然支持JSONP,可以使用$.getJSON(url,[data],[callback])方法(详细可以参考http://api.jquery.com/jQuery.getJSON/)。那我们就来修改下程序A的代码,改用jQuery的getJSON方法来实现(下面的例子没用用到向服务传参,所以只写了getJSON(url,[callback])):

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
 $.getJSON("http://localhost:20002/MyService.ashx?callback=?",function(data){
  alert(data.name + " is a a" + data.sex);
 });
</script>
Copy after login

结果是一样的,要注意的是在url的后面必须添加一个callback参数,这样getJSON方法才会知道是用JSONP方式去访问服务,callback后面的那个问号是内部自动生成的一个回调函数名。这个函数名大家可以debug一下看看,比如jQuery17207481773362960666_1332575486681。

当然,加入说我们想指定自己的回调函数名,或者说服务上规定了固定回调函数名该怎么办呢?我们可以使用$.ajax方法来实现(参数较多,详细可以参考http://api.jquery.com/jQuery.ajax)。先来看看如何实现吧:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
 $.ajax({
  url:"http://localhost:20002/MyService.ashx?callback=?", 
  dataType:"jsonp",
  jsonpCallback:"person",
  success:function(data){
   alert(data.name + " is a a" + data.sex);
  }
 });
</script>
Copy after login

没错,jsonpCallback就是可以指定我们自己的回调方法名person,远程服务接受callback参数的值就不再是自动生成的回调名,而是person。dataType是指定按照JSOPN方式访问远程服务。

相关推荐:

Jsonp的原理以及简单实现的方法

jsonp的原理,封装jsonp的方法介绍

js/ajax跨越访问-jsonp的原理和实例(javascript和jquery实现代码)_javascript技巧

The above is the detailed content of Completely master the principles and implementation of jsonp. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!