Jquery cross-origin request

Source: Internet
Author: User
Jquery cross-origin request

After jquery1.2, The getjson method supports cross-origin reading of JSON data. The principle is to use a concept called jsonp. Of course, the essence is to dynamically load JS through the script tag. It seems that this is the only way to achieve real cross-origin.

The usage of getjson has been detailed in the jquery manual. It is easy to refer to the manual. It must be noted that the jsonp used by getjson requires the cooperation between the client and the server.

  1. The URL passed by the client must contain the callback variable, in the form of callback =? . (Will jquery generate a random string replacement? To the server)
  2. The server obtains the callback value passed by the client, and forms the callbackvalue with the JSON string to be passed. '('. JSON. ')' is returned to the client (for example, PHP string connection mode, similar to other languages)

It should have been able to read data across domains.

When both JSON data is output (

In Ajax applications, the browser does not support cross-origin calls by default due to security issues. Traditional solutions include: (reference 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-client ).
Flash:
Remote host needs to deploy a crossdomain. xml file, Flash is relatively proprietary and opaque to use, requires learning a one-off moving target programming langage.
Script Tag:
Difficult to know when the content is available, no standard methodology, can be considered a "security risk ".

All of the above methods have their own shortcomings, and there are not many solutions. Later, a technology called JSON with padding, referred to as jsonp. (the principle of reference to the http://bob.pythonmac.org/archives/2005/12/05/remote-json-jsonp/), jsonp should be used to achieve cross-origin calls of JSON data. Fortunately, jquery1.2 will support jsonp Applications later. The following describes the cross-origin calls of JSON in jquery.

The Application of jsonp to implement JSON data cross-origin calling requires the cooperation between the server and the client. Reference the official jquery example. The client is deprecated 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 jsoncallback =? Is the key! The symbol is automatically replaced by the name of another callback method by query. We will ignore the specific process and principle here. What we care about is jsoncallback =? What role does it play? Originally, jsoncallback =? After the method is replaced, the method name is passed to the server. What do we do on the server? The server must accept the jsoncallback parameter and return the jsoncallback value as the JSON data method name. For example, if the server is 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 sum up, use jsonp to do two things:

1/request address and parameter: jsoncallback =?

2/The server segment transmits the jsoncallback value as the method name, for example, jquet098788 (...)

Jquery has supported XMLHTTP cross-origin requests since 1.2. How can this problem be solved?

The core principle of cross-origin access in jquery: JS file injection. Because the src attribute of the script tag can be cross-origin, the src attribute of the script tag is used to directly return data not under the current domain name, the specific method is jsonp.

Code:

Test.html, for example, at www.qq.com

<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<HTML xmlns = "http://www.w3.org/1999/xhtml">

<Head>

<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312"/>

<Title> jquery-Cross-origin request </title>

<SCRIPT type = "text/JavaScript" src = "/JS/jquery. js"> </SCRIPT>

</Head>

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

Parameters ('{msg_box'{.html (JSON. msg );

Return true;

}

});

});

</SCRIPT>

<Body>

<Div id = "msg_box"> </div>

</Body>

</Html>

Server. php, for example, at www.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, Lu asked a question about jquery's cross-origin reading of JSON data. Jquery is rarely used. I have never tried it. Find the $. getjson () method of JQ on the Internet. Let's first introduce the conceptual things and find them online. Just take a look.

1. jsonp (JSON with padding-filling JSON data is also a common JSON cross-origin method): execute a client JS function by calling a specific SRC address using the script tag, generate relative data (in JSON format) on the server and pass it to the JS function of the client in the form of parameters to execute this function, provided that the server data output is supported.

2. Why is jsonp used? Because JSON is only plain text containing simple brackets, many channels can exchange JSON messages. Because of the same-origin policy restrictions, we cannot use XMLHttpRequest when communicating with external servers. Jsonp is a method that can bypass the same-origin policy. By using the combination of JSON and <SCRIPT> tags, jsonp directly returns 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, Douban API, Del. icio. us json api, etc.

Bytes ------------------------------------------------------------------------------------------------

Like Ajax, jsonp actually already exists, but it is relatively novel (it seems to have been around for a long time ). Since version 1.2, 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 a JQ test example on the official website:

A.html

<HTML>

<Head>

<SCRIPT src = "http://code.jquery.com/jquery-latest.js"> </SCRIPT>

</Head>

<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: do_jsonp ();"> click me </a> <br/>

<Textarea id = "result" Cols = "50" rows = "3"> </textarea>

</Body>

</Html>

Profile2.php

<? PHP

$ Callback = isset ($ _ Get ['callback'])? $ _ Get ['callback']: '';

$ JSON = '';

// PHP Array

$ Arr = array (

'Name' => 'lava ',

'Nick '=> 'flatfish ',

'Contact '=> array (

'Msn '=> 'lavaguo # msn.com ',

'Email '=> 'Guo. Feng # zol.com.cn ',

'Website' => 'HTTP: // www.zol.com.cn ',

)

);

$ Arr = gb2312toutf8 ($ ARR); // convert Chinese to UTF-8

$ JSON = json_encode ($ ARR); // convert it to a JSON Array

If (! Empty ($ callback )){

$ JSON = $ callback. '('. $ JSON. ')'; // pay attention to the format. It takes some time for debugging.

}

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 that in the above example, the URL is written as a http://active.zol.com.cn/guofeng/profile2.php? Callback = ?, It should be noted that this question mark will be automatically replaced by the callback function name by jquery (if it is an anonymous function, jquery will automatically generate a time stamp function name ).

Summarize the jsonp principles:

Register a callback on the client, and then pass the callback name to the server.

In this case, the server is converted into JSON data.

Then, a function is generated in Javascript syntax. The function name is the passed parameter jsonp.

Finally, place the JSON data directly in the function as an input parameter. In this way, a JS syntax document is generated and returned to the client.

The client browser parses the script tag and executes the returned JavaScript document. As a parameter, the data is passed into the pre-defined callback function of the client. (The callback function is dynamically executed)

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.