Http://www.xuejiehome.com/blread-1627.html
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:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Server code (PHP in this example ):
<? Php $ jsonp = $ _ REQUEST ["callback"]; $ str = '[{"id": "1", "name": "Test 1 "}, {"id": "2", "name": "Test 2"}] '; $ str = $ jsonp. "(". $ str. ")"; echo $ str;?>
Demo:
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:
<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Server code:
<? Php $ str = '[{"id": "1", "name": "Test 1" },{ "id": "2", "name ": "Test 2"}] '; $ str = "OnJSONPServerResponse (". $ str. ")"; echo $ str;?>
Effect display:
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.yzswyl.cn /? Act = add such, should write all it is: http://www.yzswyl.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.