Cross-domain invocation of jquery

Source: Internet
Author: User

The JQuery1.2 post-Getjson method supports reading JSON data across domains, using a concept called JSONP. Of course, the essence of this is the dynamic loading of JS through the script tag, which seems to be the only way to achieve true cross-domain.

The use of Getjson jquery Handbook has been written in detail, the reference manual can be, very simple. One point to note is that the JSONP used by Getjson requires the client to cooperate with the server.

    1. The URL passed by the client should contain the callback variable, ending in the form of a callback=. (jquery randomly generates a string substitution?) Delivered to the service side)
    2. The server gets the value of the callback passed by the client Callbackvalue, and the JSON string that needs to be passed constitutes callbackvalue. ' ('. Json. ') ' Passed back to the client (example of a PHP string connection, similar to other languages)

It should have been possible to read across domains without an accident.

While outputting JSON data, the previous (

Ajax applications, because of security issues, the browser is not supported by default cross-domain calls. Traditional solutions, including: (Ref. http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/)

Local Proxy:
Needs infrastructure (CAN ' t run a serverless client) and you get double-taxed on bandwidth and latency (remote-proxy-c lient).
Flash:
Remote host needs to deploy a crossdomain.xml file, Flash was relatively proprietary and opaque to use, requires learning a One-off moving target programming langage.
Script tag:
difficult to know when the content was available, no standard methodology, can be considered a "security risk".

All of the above methods are flawed and are not a lot of solutions. Then came a technique called JSON with Padding , referred to as JSONP . (Principle Reference http://bob.pythonmac.org/archives/2005/12/05/ remote-json-jsonp/), application Jsonp can implement cross-domain invocation of JSON data. Very fortunate, JQuery1.2 later support the application of JSONP. The following focuses on the cross-domain invocation of JSON in jquery.

Applying JSONP to cross-domain calls of JSON data requires a server-side collaboration with the client. Citing The official jquery example, the client side is dropped as follows:

$.getjson ("Http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json &jsoncallback=? ",
function (data) {
$.each (Data.items, function (I,item) {
$ (" if (i = = 3) return false;
});
});

Note that the address in the call here jsoncallback=? is the key! Where the symbol is automatically replaced by query with the name of the other callback method, the specific process and principle we do not care about here. We are concerned about the role of jsoncallback=? The original jsoncallback=? After being replaced, the method name is passed to the server. What do we do on the server side? The server will accept the parameter Jsoncallback and then return the value of Jsoncallback as the JSON data method name, such as the server is a JSP, we will do this:

...

String jsoncallback=request.getparameter ("Jsoncallback");

...

Out.print (jsoncallback+ "({\" account\ ": \" xx\ ", \" passed\ ": \" true\ ", \" error\ ": \" Null\ "});

The data obtained by jquery may be as follows:

JQUET0988788 ({"Account": "XX", "passed": "True", "error": "NULL"})

To summarize, two things to do with JSONP:

1/Request address plus parameter: jsoncallback=?

2/server segment returns the value of Jsoncallback as a method name, such as JQUET098788 (...)

jquery supports XMLHTTP cross-domain requests from 1.2 onwards, how do I do it?

The core principle of cross-domain access in jquery: JS file injection because the SRC attribute of the script tag can be cross-domain , using the src attribute of the script tag to return the data directly from the non-domain name, in the way called: Jsonp.

Code:
test.html, for example in www.qq.com
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "HTTP://WWW.W3.ORG/TR/XHTML1/DTD/XHTML1-TRANSITIONAL.DTD">
http://www.w3.org/1999/xhtml">
<meta http-equiv= "Content-type" content= "text/html; charset=gb2312 "/>
<title>jquery-cross-domain request </title>
<script type= "Text/javascript" src= "/js/jquery.js" ></script>
<script type= "Text/javascript" >
JQuery (document). Ready (function () {
$.ajax ({
Type: "GET",
URL: "http://www.b.com/server.php&action=getmsg&Callback =?",
dataType: "Jsonp",
JSONP: ' Callback ',
Success:function (JSON) {
$ (' #msg_box '). HTML (JSON.MSG);
return true;
}
});
});
</script>
<body>
<div id= "Msg_box" ></div>
</body>

server.php, for example inwww.baidu.com
<?php
$action = $_get[' action '];
$callback = $_get[callback];

if ($action)
{
echo "{$callback} ({" MSG ":" This is a jquery Jsonp test message! "})";
Exit ();
}
Else
    {
echo "{$callback} ({" MSG ":" Error Action! "})";
Exit ();
}
?>

This morning, Passepartout asked a jquery question about reading JSON data across domains. jquery is used very little, and it really hasn't actually been tried. So find a search on the internet, see the JQ $.getjson () method. First introduce the concept of things, online search, simple look on the line.

1.JSONP (JSON with padding-to populate JSON data is the usual JSON cross-domain approach): Using the script tag, through the invocation of a specific SRC address, to execute a client's JS function, The server side generates relative data (in JSON format) and passes it as a parameter to the client's JS function and executes this function, provided the server-side data output support is required.

2. Why use JSONP: Because JSON is just plain text with a simple parenthesis structure, many channels can exchange JSON messages. Because of the limitations of the same-origin policy, we cannot use XMLHttpRequest when communicating with external servers. Jsonp is a way to bypass the same-origin strategy by using JSON with the <script> tag to directly return executable JavaScript function calls or JavaScript objects from the server.

3. Who is using Jsonp:dojo, JQuery, Youtube GData API, Google social Graph API, Digg API, GeoNames WebService, Watercress API, Del.icio.us JSON A Pi and so on.

------------------------------------------------------------------------------------------------


Like AJAX, JSONP is actually already there, but it's relatively new (and seems to come out for a long time). Since the 1.2 release, jquery has added support for JSONP (Http://docs.jquery.com/Ajax/jQuery.getJSON#urldatacallback). We can easily use the $.getjson () method (or other $.ajax ()-based methods) to load JSON data across domains. I wrote an example of the JQ test on the official website:

A.html

<script src= "Http://code.jquery.com/jquery-latest.js" ></script>
<body>
<script type= "Text/javascript" >
function Do_jsonp () {
$.getjson ("http://active.zol.com.cn/guofeng/profile2.php?callback=?",
function (data) {
$ (' #result '). Val (' My name is: ' + Data.nick);
});
}
</script>
<a href= "JavaScript:d O_jsonp (); >click me</a><br/>
<textarea id= "Result" cols= "rows=" 3 "></textarea>
</body>

profile2.php

<?php
$callback = Isset ($_get[' callback ')? $_get[' callback ': ';
$json = ";

PHP arrays
$arr = Array (
' Name ' = ' lava ',
' Nick ' = ' halibut ',
' Contact ' = = Array (
' MSN ' = ' lavaguo#msn.com ',
' Email ' = ' guo.feng#zol.com.cn ',
' website ' = ' http://www.zol.com.cn ',
)
);

$arr = Gb2312toutf8 ($arr);//Chinese need to turn UTF-8
$json = Json_encode ($arr);//Turn into a JSON array
if (!empty ($callback)) {
$json = $callback. ' ('. $json. '///Pay attention to the format here, it takes a little time to debug
}
Echo $json;

Function Gb2312toutf8 (& $input)
{
if (!is_array ($input)) {
$input = Iconv (' GB2312 ', ' UTF-8 ', $input);
} else {
foreach ($input as $k = = $v) {
Gb2312toutf8 (& $input ["$k"]);
}
}
return $input;
}

?>

You may have noticed in the example above that the URL was written as http://active.zol.com.cn/guofeng/profile2.php?callback=, and it is important to note that this question mark will be Automatically replaced with the function name of the callback function (if it is an anonymous function, JQuery will automatically generate a time-stamped letter name).

Summarize the following JSONP principle:

First register a callback with the client and then pass the callback name to the server.

At this point, the server becomes JSON data.

Then, in JavaScript syntax, a function is generated, and the function name is the parameter Jsonp passed up.

Finally, the JSON data is placed directly into the function in the form of a parameter, so that a document of JS syntax is generated and returned to the client.

The client browser parses the script tag and executes the returned JavaScript document, where the data is passed in as a parameter to the client's pre-defined callback function. (Dynamic execution callback function)

Cross-domain invocation of jquery

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.