Home >Web Front-end >JS Tutorial >Understand at a glance: Detailed explanation of jsonp_jquery

Understand at a glance: Detailed explanation of jsonp_jquery

WBOY
WBOYOriginal
2016-05-16 15:57:23943browse

I believe that everyone uses json a lot. I have never had the opportunity to use jsonp, but I often see it. I only know that it is "used for cross-domain" and I never know what it is. I finally figured it out today. Let’s step by step to figure out what jsonp is.

Same Origin Policy

First of all, for security reasons, browsers have a mechanism called the same-origin policy. The same-origin policy prevents documents or scripts loaded from one source from getting or setting the attributes of documents loaded from another source. It seems that I don’t know what it means, but you will know it after you practice it.

1. Create two web pages at will

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

2. Use jQuery to initiate requests from different sources
Add a button to the web page on port 2698, and the Click event will initiate two requests to the domain with port 2701.

Copy code The code is as follows:

$("#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.

Cross-domain capability of script tag
I don’t know if you know about CDN, such as Microsoft’s CDN. Using it, our web pages do not need to provide jQuery, and Microsoft’s website will provide it for us:

Copy code The code is as follows:



Back to our 2698 port web page, above we have a request for the jQuery file in the 2701 port domain in the Click event, this time using the script tag to request.
Copy code The code is as follows:



Of course, 200, OK

The same webpage with port 2698 initiates a request for the 2701 domain. Setting the scr attribute in the script is OK, but the other way is tragic. Taking advantage of the cross-domain capabilities of script, this is the basis of jsonp.

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:

Copy code The code is as follows:

function CreateScript(src) {
$("<script><//script>").attr("src", src).appendTo("body")<br> }<br> </div> <br> Add a button event to test it out: <br> <div class="codetitle"> <span><a style="CURSOR: pointer" data="4331" class="copybut" id="copybut4331" onclick="doCopy('code4331')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code4331"> <br> $("#getOtherDomainJson").click(function () {<br> $.get('http://localhost:2701/home/somejson', function (data) {<br> console.log(data)<br> })<br> })<br> </div> <p><img src="http://files.jb51.net/file_images/article/201506/20156190709927.png?2015519722" alt=""></p> <p>First of all, in the first browser, the Url http://localhost:2701/home/somejson does have a json, and using the script tag on the 2698 web page to request the 2701 Url is also 200 OK, 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. </p> <p>Use script to obtain foreign jsonp</p> <p>Obviously, putting the above json into a callback method is the easiest way. For example, it becomes like this: </p> <p><img src="http://files.jb51.net/file_images/article/201506/20156190730417.png?2015519738" alt=""></p> <p>If the jsonpcallback method exists, then jsonpcallback({"Email":"zhww@outlook.com","Remark":"I come from the far east"}) is a legal js statement. </p> <p>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, as above It's "callback". </p> <p>Add callback function: <br> </p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="86577" class="copybut" id="copybut86577" onclick="doCopy('code86577')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code86577"> <br> function jsonpcallback(json) {<br> console.log(json)<br> }<br> </div> <br> Slightly change the parameters of the previous method: <br> <div class="codetitle"> <span><a style="CURSOR: pointer" data="13280" class="copybut" id="copybut13280" onclick="doCopy('code13280')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code13280"> <br> $("#getJsonpByHand").click(function () {<br> CreateScript("http://localhost:2701/home/somejsonp?callback=jsonpcallback")<br> })<br> </div> <p><img src="http://files.jb51.net/file_images/article/201506/20156190749818.png?2015519756" alt=""></p> <p>200OK, the server returns jsonpcallback({"Email":"zhww@outlook.com","Remark":"I come 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. </p> <p><strong>Use jQuery to get jsonp</strong><br> In the above method, you need to insert a script tag and define a callback, which is a bit troublesome. You can use jQuery to directly get the desired json data, the same as the above jsonp: <br> </p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="33170" class="copybut" id="copybut33170" onclick="doCopy('code33170')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code33170"> <br> $("#getJsonpByJquery").click(function () {<br> $.ajax({<br> ​ ​ url: 'http://localhost:2701/home/somejsonp',<br>          dataType: "jsonp",<br>          jsonp: "callback",<br> Success: function (data) {<br> console.log(data)<br> }<br> })<br> })<br> </div> <br> The results obtained are similar to the above. <p><strong>Summary</strong></p> <p>In one sentence, you can use the script tag to bypass the same-origin policy and obtain data like this. jsonpcallback is the callback method that exists on the page, and the parameter is the desired json. <br> </p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="58" class="copybut" id="copybut58" onclick="doCopy('code58')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code58"> <br> jsonpcallback({"Email":"zhww@outlook.com","Remark":"I come from the far east"})<br> </div> <p>ADD native js:<br> </p> <div class="codetitle"> <span><a style="CURSOR: pointer" data="99395" class="copybut" id="copybut99395" onclick="doCopy('code99395')"><u>Copy code</u></a></span> The code is as follows:</div> <div class="codebody" id="code99395"> <br> <button id="btn">click</button><br> <script type="text/javascript"><br>     function $(str){<br>         return document.getElementById(str)<br>     }<br>     function CreateScript(src) {<br>         var Scrip=document.createElement('script');<br>         Scrip.src=src;<br>         document.body.appendChild(Scrip);<br>     }<br>     function jsonpcallback(json) {<br>             console.log(json);//Object { email="中国", email2="中国222"}<br>     }<br>     $('btn').onclick=function(){<br>       CreateScript("http://localhost:51335/somejson?callback=jsonpcallback")    <br>     }<br> </script>
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