Home  >  Article  >  Web Front-end  >  Completely master the principles and implementation of jsonp

Completely master the principles and implementation of jsonp

小云云
小云云Original
2018-01-18 09:32:061566browse

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)
})
})

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

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) {
 $("

程序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的部分代码:

程序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数据传入这个方法完成回调。有点罗嗦了,还是看看实现代码吧:

这个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])):


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

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


没错,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!

Statement:
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