Jsonp:js cross-domain

Source: Internet
Author: User

JSONP is a shorthand for JSON with padding (packed JSON or parametric JSON), a new way to apply JSON, often used for server-to-client cross-origin communication, which is popular in later Web services. This article will cover the details of JSONP

The basic idea of JSONP is that Web pages request JSON data from the server by adding a <script> element, which is not subject to the same-origin policy; When the server receives the request, it returns the data in a callback function with the specified name.

When data is invoked through the <script> element, the response content must be wrapped in a JavaScript function name and parentheses. Instead of sending JSON data like this, that's what p means in Jsonp.

[1, 2, {"Buckle": "My Shoe"}]

Jsonp looks like JSON, just a JSON that is contained in a function call, and it sends a JSON response after such a package:

Handleresponse ([L, 2, {"Buckle": "My Shoe"}])

  

The response after the package becomes the content of the <script> element, which first determines the JSON-encoded data and then passes it to the handleresponse () function

In practice, a service that supports JSONP does not enforce specifying the name of a callback function that the client must implement, such as Handleresponse. Instead, they use the value of the poll parameter to allow the client to specify a function name and then populate the response with the function name. Many services that support JSONP can tell the name of the parameter. Another common parameter name is callback, in order for the service to be used to support similar special requirements, you need to make some changes to the code

JSONP consists of two parts: the callback function and the data. A callback function is a function that should be called in the page when the response arrives. The name of the callback function is typically specified in the request. The data is the JSON data that is passed into the callback function

Http://freegeoip.net/json/?callback=handleResponse

  

This URL is requested in a JSONP geolocation service. It is common to specify the callback parameters of the JSONP service by consulting the string, as shown in the URL above, and the callback function specified here is named Handleresponse ().

JSONP is used by dynamic <script> elements, and can be used to specify a cross-domain URL for the src attribute. The <script> element here is similar to the element and has the ability to load resources from other domains without restriction. Because JSONP is a valid JavaScript code, it executes immediately after the request is completed, after the JSONP response is loaded into the page.

function Handleresponse (response) {    alert ("You ' re at IP address" + Response.ip + ", which are in" + Response.city + " , "+ Response.region_name);} var script = document.createelement ("script"); script.src = "Http://freegeoip.net/json/?callback=handLeResponse"; Document.body.insertBefore (script, document.body.firstChild);

  

The main reason why Jsonp is very popular among developers is that it is very easy to use, full support for older browsers, and very small server retrofits. Compared to image Ping, it has the advantage of having direct access to the response text, enabling two-way communication between the browser and the server

Use the <script> element for AJAX transmission, which is not affected by the same-origin policy, so you can use them to request data from other servers, and the responses that contain JSON-encoded data are automatically decoded (that is, executed).

However, JSONP also has two deficiencies: first, JSONP is loading code execution from other domains. If the other domains are unsafe, it is likely that some malicious code will be entrained in the response, and there is no way to pursue this at this point except to completely abandon the JSONP call. Therefore, when you use a Web service that is not your own operation, you must ensure that it is safe and reliable, and secondly, it is not easy to determine whether the JSONP request failed. Although HTML5 has added a onerror event handler to the <script> element, it has not yet been supported by any browsers. To do this, the developer had to use a timer to detect whether a response was received within the specified time. But even if this is not satisfactory, after all, not every user Internet speed and bandwidth are the same

Simple example

Front-end

<button id= "BTN" > Get information </button><div id=" result "></div    ><script>var add = (function () {var counter = 0;    return function () {return ++counter;    }}); function Loadscript (URL) {loadscript.mark = ' load ';    var script = document.createelement ("script");    Script.type = "Text/javascript";    script.src = URL;        Script.onload = function () {Img.style.display = ' none ';    Btn.removeattribute (' disabled '); } document.body.appendChild (script);} function test (data){var sum = Add ()-1;        if (Sum < data.length) {result.innerhtml + = Data[sum];    }}btn.onclick = function () {img.style.display = ' inline-block ';    Btn.setattribute (' disabled ', '); Loadscript (' Https://www.webhuochai.com/test/getData.php?callback=test ');}    </script>

  

"Back End"

<?phpfunction Test_input ($data) {    $data = trim ($data);    $data = Stripslashes ($data);    $data = Htmlspecialchars ($data);    return $data;} $arr = [1,2,3,4,5];echo test_input ($_get[' callback ']). " (". Json_encode ($arr)."); ";? >

  

Baidu Search Box

Baidu search box is the use of JSONP technology, in the Baidu search URL, the useful query is as follows

Https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=123&&cb=a

  

The result is:

A ({Q: "123", p:false,s:["12306", "12306 Railway Customer Service Center", "12308 car booking official website", "12306 train ticket online booking official website", "12333", "12315", "12345", " 12333 Social Security Enquiry Net "," 123 website Home "," 12366 "]});

  

Therefore, WD is the keyword, CB used to jsonp the function name. In the data obtained, S is the data that is composed of the data starting with the keyword

Baidu Search key URL is as follows

Https://www.baidu.com/s?wd=a

  

WD is the keyword, when wd=a, will open the keyword for a page

<style>body{margin:0;} Ul{margin:0;padding:0;list-style:none;} A{color:inherit;text-decoration:none;} input{padding:0;border:0;}. box{width:340px;height:38px;border:2px solid Gray;}. Con{overflow:hidden;}. input{float:left;width:300px;height:38px;}. Search{width:38px;height:38px;float:right;background:url (' http://sandbox.runjs.cn/uploads/rs/26/ddzmgynp/ Search.png ') 0-38px;}. list{position:absolute;width:298px;border:1px solid #e6e8e9; overflow:hidden;}. in{line-height:30px;border-bottom:1px solid lightblue;cursor:pointer;text-indent:1em;}. List. In:last-child{margin-bottom: -1px;}. In:hover{background-color: #f9f9f9;}        </style><div class= "box" id= "box" > <div class= "con" > <input class= "input" id= "search" > <a target= "_blank" id= "btn" href= "javascript:;" class= "search" ></a> </div> <ul class= "lis T "id=" list "></ul> </div> <script>function loadscript (URL) {Loadscript.mark = 'Load ';    var script = document.createelement ("script");    Script.type = "Text/javascript";    script.src = URL; Document.body.appendChild (script);}        function callback (data) {if (data) {var arr = data.s;        var html = '; for (var i = 0,len = Arr.length, i < Len; i++) {html+= "<li class= ' in ' ><a href= ' https://www.baidu.co m/s?wd= "+ arr[i]+" ' target= ' _blank ' style= ' display:block ' > "+ arr[i]+" </a></li> "} List.inne            RHTML = html;    }}search.onkeyup = function (e) {e = e | | event;    if (E.keycode = = ') {window.open (' https://www.baidu.com/s?wd= ' + this.value); } if (This.value) {if (Search.data! = this.value) {btn.setattribute (' href ', ' https://www.baidu.com/s?wd=            ' + this.value);            var = this;        Loadscript ("https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su?wd=" + that.value + "&&cb=callback");    }}else{list.innerhtml = ";    }Search.data = This.value;}    Search.onclick = function (e) {e = e | | event;    List.style.display = ' block ';    if (e.stoppropagation) {e.stoppropagation ();    }else{e.cancelbubble = true; }}document.onclick = function () {List.style.display = ' none ';} </script>

  

Jsonp:js cross-domain

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.