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
HTML code
- <! 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
Java code
- 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 ();
- }
- }
- }