Js/ajax Cross Access-jsonp principles and examples (JavaScript and jquery implementation code) _javascript tips

Source: Internet
Author: User
Tags script tag
I am glad that I have seen the new sun rise after the end of the day, so I can also write articles here, to go back to Kazakhstan, recently done a project, need to use the subdomain domain name to invoke an existing function under the main domain name, so thought of using JSONP to solve, in our ordinary projects there are no lack of such a need for friends, So I write it down so that I can check it out and hope to help you.

What is the JSONP protocol?
JSONP is the JSON with Padding. Due to the restriction of the homology policy, XMLHttpRequest only allows resources to be requested for the current source (domain name, protocol, port). If Cross-domain requests are to be made, we can make cross-domain requests by using the HTML script tag and return the script code to execute in the response, where the JavaScript object can be passed directly using JSON. This cross-domain mode of communication is called JSONP.
It is clear that JSONP is a scripting Injection (script injection) behavior that requires special attention to its security.

examples of Jsonp in jquery
We need two pages to assume the client and server side roles of the protocol respectively.

Client Code
Copy Code code as follows:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
&LT;TITLE&GT;JSONP Test Example </title>
<script type= "Text/javascript" src= "Http://www.xxxxxxxxxxxx.cn/js/jquery.min.js" ></script>
<script type= "Text/javascript" >
JQuery (document). Ready (function () {
$.ajax ({
Type: "Get",
Async:false,
URL: "http://www.xxxxxxxxxxxx.cn/demos/jsonp.php",
DataType: "Jsonp",
JSONP: "Callback",//passed to the request handler or page to obtain the parameter name of the JSONP callback function name (general default: Callback)
Jsonpcallback: "Feedbackstate",//Custom JSONP callback function name, default to jquery automatically generated random function name
Success:function (data) {
var $ul = $ ("<ul></ul>");
$.each (Data,function (i,v) {
$ ("<li/>"). Text (v["id"] + "" + v["name"). Appendto ($ul)
});
$ ("#remote"). Append ($ul);
},
Error:function () {
Alert (' fail ');
}
});
});
</script>
<body>
Remote data is as follows:<br/>
<div id= "remote" ></div>
</body>

Service-side code (this example uses PHP)
Copy Code code as follows:

<?php
$JSONP = $_request["Callback"];
$str = ' [{' id ': ' 1 ', ' name ': ' Test 1 '},{' id ': ' 2 ', ' name ': ' Test 2 '}] ';
$str = $jsonp. "(". $str. ")";
Echo $str;
?>


the principle and simple example of Jsonp
jquery is encapsulating it, you may not see the real implementation, and we use one of the following examples to illustrate:
Client code:
Copy Code code as follows:

<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/>
&LT;TITLE&GT;JSONP Test Example </title>
<script type= "Text/javascript" src= "Http://www.xxxxxxxxxxxx.cn/js/jquery.min.js" ></script>
<script type= "Text/javascript" >
function Calljsonpserver (URL) {//Call JSONP server, URL is request server address
var oldscript =document.getelementbyid (URL); If the calling server is registered in the page, the call is called again
if (oldscript) {
Oldscript.setattribute ("src", url);
Return
}
var script =document.createelement ("script"); If the server is not registered, register and request the
Script.setattribute ("type", "Text/javascript");
Script.setattribute ("src", url);
Script.setattribute ("id", URL);
Document.body.appendChild (script);
}
function Onjsonpserverresponse (data) {
var $ul = $ ("<ul></ul>");
$.each (Data,function (i,v) {
$ ("<li/>"). Text (v["id"] + "" + v["name"). Appendto ($ul)
});
$ ("#remote"). Append ($ul);
}
</script>
<body>
<input type= "button" value= "Click to get Remote Data" onclick= "Calljsonpserver (' Http://www.xxxxxxxxxxxx.cn/demos/jsonp_ original.php ') "/>
<div id= "remote" ></div>
</body>

Service-side code
Copy Code code as follows:

<?php
$str = ' [{' id ': ' 1 ', ' name ': ' Test 1 '},{' id ': ' 2 ', ' name ': ' Test 2 '}] ';
$str = "Onjsonpserverresponse (". $str. ")";
Echo $str;
?>


Other than to say, I believe that the code you should understand how it is achieved.
need to be aware
1. Because of the use of jquery in AJAX processing is the UTF-8 encoding transmission parameters, so the JSONP processing end with UTF-8 encoding is the best, so save the code conversion, if not utf-8 remember to convert, otherwise Chinese will garbled.
2. The requested service-side URL is best not written as http://www.xxxxxxxxxxxx.cn/?act=add such, should write all of its: Http://www.xxxxxxxxxxxx.cn/index.php?act=add such, Incompatibilities have occurred in the course of application.
This is OK, if a friend encountered what problems can be sent up to communicate with everyone.
Welcome to reprint, reprint please indicate the original include links must be added, otherwise ... Omit N words here
Signature: To communicate together, to learn together, to help people in need, to work together towards the road to success.
Related Article

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.