Implementing Cross-domain requests with JSONP

Source: Internet
Author: User
Tags format functions html page json log php code resource domain

Foreword: Sometimes a busy to have no time idea, originally I already had more than 10 days did not write a blog. Always want to do cross-domain aspects of the attempt, but recently prepared school recruit no time to move hands. Today to talk about Jsonp bar, last night in the QQ space log inside the network pictures of the problem, I found that the log also provides HTML mode, we can use the IMG tag src attributes to achieve cross-domain request, from their own server to extract dynamic content.

JSONP

Before we talk about implementation, let's take a look at what JSONP is. Here's what Wikipedia explains:

JSONP or "JSON with padding" are a communication technique used in JavaScript programs running into Web browsers to request D ATA from-a server in a different domain, something prohibited by typical web browsers because of the Same-origin policy. JSONP takes advantage of the fact that browsers don't enforce the Same-origin policy on <script> tags. Since It works through <script> tags, JSONP supports only the "GET Request" method. There are significant security implications and risks associated to using JSONP; Unless you have no choice and CORS is usually the better choice.

I humble translation: Jsonp also known as JSON with padding, it is used in the browser running in a JS program in an interactive technology, in order to request data from different server domain names. Due to the restriction of homologous policy, some functions will be prohibited by the browser. JSONP is using browsers that do not have a homologous policy for <script> labels. And because it works through <script>, JSONP only supports get requests. However, it is worth noting that the use of JSONP will have security risks and dangers. CORS (cross-domain resource sharing, cross-origin Resource sharing) is a more commonly used choice, unless you have no choice.

Explain:

Simply put, in general, the pages in this domain want to get the data under other domain names will be limited. However, <script> (Img,iframe) in the HTML page breaks through this limitation by accessing other domain names through the SRC attribute and obtaining the returned data, but this method is not secure and can only be obtained through a GET method.

In fact, we usually a little attention, it is not difficult to find in fact, we usually use CDN in the page is also this principle, our page can also access the other server JS files.

such as our common Baidu Cdn, we usually add <script> tags in
<script src= "Http://apps.bdimg.com/libs/jquery/2.1.4/jquery.js" ></script>

The only slight difference is that it now turns to running file request data to the server and then returning as JavaScript.

Client implementation:

JSONP is an informal transport protocol in which the content and format can be defined by the user. However, I think Jsonp may be added to the ES6, maybe Oh, then it may be standardized transmission format. Jsonp one of the key points is to allow the user to pass a callback parameter to the server, and then the server output data as callback parameters are returned to the client page, and finally based on the parameters of the client page to execute this callback function, and finally achieve the return data and processing purposes.

The code form is as follows:


<meta charset= "UTF-8" >
<title>JSONP</title>
<script type= "Text/javscript" >
var CBFN = function (str) {
alert (str);
}
</script>
<script src= "Http://www.sp0.baidu.com?data=value&cb=cbFn" ></script>



First you have to predefined a callback function to process the return data, and then request the data <script> label SRC to pass the request parameters and callback function names to the background, which should be communicated and coordinated.

Because the request address, the request parameter and the number of times in the actual application are not fixed, we should encapsulate the JSONP into a function to enhance flexibility and reusability.


var S1;
function Jsonp (URL,DATA,CB) {
DATA.CB = CB?CB: "Callback";
DATA.T = new Date (). GetTime ();
for (var i in data) {
var str = i+ "=" +data[i];
Arr.push (str);
}
var str = url+ "?" +arr.join ("&");
var Headel = document.getElementsByTagName ("head") [0];
if (S1) {
Headel.removechild (S1);
}
S1 = document.createelement ("script");
S1.SRC = str;
Headel.appendchild (S1);
}



Code Explanation: First, insert a callback function name and a new time parameter value for the passed data, and let the background get the name of the functions you want to callback and prevent the call cache. The next step is to determine if the JSONP request has been sent before, and if so, to delete the rebuild.

Service-Side implementation:

Suppose I execute the following request on the client


Jsonp ("http://www.chengguanhui.com/test.php", {
Name: "Ray",
Age:23
}, "CBFN");

CBFN (str) {
alert (str);
}



Then the URL passed by HTTP is http://www.chengguanhui.com/test.php?name=ray&age=23cb=cbFn&t=242566 (an indefinite time value)

PHP Code:


<?php
Require_once ("common.php");
$name = $_get[' name '];
$age = $_get[' age '];
$CB = $_get[' CB '];
$str = $name. $age;
echo $CB. " (". $str.") ";
?>



The client receives the CBFN ("Ray23") and pops the corresponding content.

JQ implementation:

$.ajax (Url,[settings])


$.ajax ({
Type: "Get",
URL: "http://www.chengguanhui.com/test.php",
DataType: "Jsonp",
Data: "Name=ray&age=23",
JSONP: "Callback",//passed to the request handler or page to obtain the parameter name of the JSONP callback function name (general default: Callback)
Jsonpcallback: "Handlefn",//Custom JSONP callback function name, default to jquery automatically generated random function name, also can write "?", jquery will automatically process the data for you
Success:function (JSON) {
alert (json.name+json.age);
},
Error:function () {
Alert (' fail ');
}
});
});





$.getjson (Url,data,callback)


$.getjson ("http://www.chengguanhui.com/test.php",//if the request value is fixed, you can omit the data parameter and write it directly in the URL parameter.)
{
Name:ray,
Age:23
},
function (data) {
$.each (Data.items, function (I,item) {
alert (I+item);
});
});



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.