JSONP (JSON with Padding) is a "usage pattern" of data format JSON that allows Web pages to obtain data from other domains.
For more detailed information on JSONP, please refer to http://baike.baidu.com/view/2131174.htm, below is an example:
I. Client
- <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <Meta http-equiv= "content-type" content= "text/html; Charset=utf-8 ">
- <title>insert title here</title>
- <script type="Text/javascript" src="Resource/js/jquery-1.7.2.js"></ Script>
- </head>
- <script type="Text/javascript">
- $ (function () {
- /*
- Abbreviated form, the effect is the same
- $.getjson ("Http://app.example.com/base/json.do? sid=1494&busiid=101&jsonpcallback=? ",
- function (data) {
- $ ("#showcontent"). Text ("Result:" +data.result)
- });
- */
- $.ajax ({
- Type: "Get",
- Async:false,
- URL: "Http://app.example.com/base/json.do?" sid=1494&busiid=101 ",
- DataType: "Jsonp",//data type is JSONP
- JSONP: "Jsonpcallback",//parameter for the server to receive the function name of the callback call
- Success:function (data) {
- $ ("#showcontent"). Text ("Result:" +data.result)
- },
- Error:function () {
- Alert (' fail ');
- }
- });
- });
- </Script>
- <body>
- <div id="showcontent">result:</div>
- </body>
- </html>
Two. Server-side
- Import java.io.IOException;
- Import Java.io.PrintWriter;
- Import Java.util.HashMap;
- Import Java.util.Map;
- Import Javax.servlet.http.HttpServletRequest;
- Import Javax.servlet.http.HttpServletResponse;
- Import Net.sf.json.JSONObject;
- Import Org.springframework.stereotype.Controller;
- Import org.springframework.web.bind.annotation.RequestMapping;
- @Controller
- Public class Exchangejsoncontroller {
- @RequestMapping ("/base/json.do")
- public void Exchangejson (httpservletrequest request,httpservletresponse response) {
- try {
- Response.setcontenttype ("Text/plain");
- Response.setheader ("Pragma", "No-cache");
- Response.setheader ("Cache-control", "No-cache");
- Response.setdateheader ("Expires", 0);
- map<string,string> map = new hashmap<string,string> ();
- Map.put ("result", "content");
- PrintWriter out = Response.getwriter ();
- Jsonobject Resultjson = jsonobject.fromobject (map); //Assemble JSON as needed
- String jsonpcallback = Request.getparameter ("Jsonpcallback"); Client Request Parameters
- Out.println (jsonpcallback+"(" +resultjson.tostring (1,1) +")"); Return JSONP Format Data
- Out.flush ();
- Out.close ();
- } catch (IOException e) {
- E.printstacktrace ();
- }
- }
- }
JQUERY+AJAX+JSONP Cross-domain access