Fortunately, I saw the rising sun after the last day, so I was able to write articles here to get down to the truth. I recently made a project, we need to use a subdomain name to call an existing function under the primary domain name, so we thought of using jsonp to solve the problem. In our common projects, there are many friends who have such requirements, so I recorded it for future reference and hoped it could help you.
What is the JSONP protocol?
JSONP is JSON with Padding. Due to the same-origin policy restrictions, XmlHttpRequest only allows requests to resources of the Current Source (domain name, protocol, port. For cross-origin requests, we can use the html script tag to perform cross-origin requests, and return the script code to be executed in the response, where javascript objects can be directly transmitted using JSON. This cross-origin communication method is called JSONP.
Obviously, JSONP is a Script Injection behavior and requires special attention to its security.
Jsonp instance in Jquery
We need two pages to assume the client and server roles of the Protocol respectively.
Client code:Copy codeThe Code is as follows: <! 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>
<Title> 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", // The parameter name that is passed to the request handler or page to obtain the jsonp callback function name (generally: callback by default)
JsonpCallback: "feedBackState", // custom jsonp callback function name. The default value is the random function name automatically generated by jQuery.
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>
</Head>
<Body>
The remote data is as follows: <br/>
<Div id = "remote"> </div>
</Body>
</Html>
Server code (PHP in this example):Copy codeThe Code is as follows: <? Php
$ Jsonp = $ _ REQUEST ["callback"];
$ Str = '[{"id": "1", "name": "Test 1" },{ "id": "2", "name ": "Test 2"}] ';
$ Str = $ jsonp. "(". $ str .")";
Echo $ str;
?>
Jsonp principles and simple examples
Jquery encapsulates it, and you may not see the actual implementation method. We use the following example to describe it:
Client code:Copy codeThe Code is as follows: <! 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">
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/>
<Head>
<Title> 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 the JSONP server. The url is the request server address.
Var oldScript = document. getElementById (url); // If the called server is registered on the page, call the server again.
If (oldScript ){
OldScript. setAttribute ("src", url );
Return;
}
Var script = document. createElement ("script"); // if the server is not registered, register and request
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>
</Head>
<Body>
<Input type = "button" value = "click to obtain remote data" onclick = "CallJSONPServer ('HTTP: // www.xxxxxxxxxxxx.cn/demos/jsonp_original.php')"/>
<Div id = "remote"> </div>
</Body>
</Html>
Server code:Copy codeThe Code is as follows: <? Php
$ Str = '[{"id": "1", "name": "Test 1" },{ "id": "2", "name ": "Test 2"}] ';
$ Str = "OnJSONPServerResponse (". $ str .")";
Echo $ str;
?>
Let's not talk about it much. I believe you should understand how the code is implemented.
Note::
1. because jquery uses UTF-8 encoding to pass Parameters in ajax processing, it is best to use UTF-8 encoding on the jsonp processing end, which saves coding and conversion time. If it is not UTF-8, remember to convert, otherwise, Chinese characters are garbled.
2. The requested server url is better not to be written as a http://www.xxxxxxxxxxxx.cn /? Act = add such, should write all it is: http://www.xxxxxxxxxxxx.cn/index.php? Act = add is incompatible with the application process.
This is OK. If you have any questions, you can share them with us.
You are welcome to repost the article. Please indicate that the original article, including the link, must be added. Otherwise, n words will be omitted here.
Signature: Exchange, learn, and help people who need help to achieve success.