70241481
The JS code of the page
functionGetData () {$.ajax ({vard1=$ ("#d11"). Val (); URL:"Test/demopage1.do", type:"GET", Async:false, Beforesend:function(Request) {}, data: {dtp1:d1,}, DataType:' Jsonp ', Jsonp:' Callback ', Crossdomain:true,/*The default is False, remember to change to true, otherwise you will not be able to successfully obtain data data and jump to success*/Jsonpcallback:"Callback", Success:function(data) {alert ("Success"); }, Error:function(XMLHttpRequest, Textstatus, Errorthrown) {alert (xmlhttprequest.status); alert (xmlhttprequest.readystate); alert (textstatus); } });
Processing in the background (STRUTS2 is used here)
@Action (value = "DemoPage1", results = @Result (type = "json", params = {"Root", "result" })) PublicString Getpage1data () {Map<String,String> map =NewHashmap<string,string>(); Map.put ("Result", "content"); Jsonobject Resultjson=jsonobject.fromobject (map); HttpServletResponse Response=Servletactioncontext.getresponse (); HttpServletRequest Resquest=servletactioncontext.getrequest (); Response.setcontenttype ("Text/plain"); Response.setheader ("Pragma", "No-cache"); Response.setheader ("Cache-control", "No-cache"); Response.setheader ("Access-control-allow-origin", "*");//Add cross-domain accessResponse.setdateheader ("Expires", 0); //String callback= request.getparameter ("callback");//If you add callback after the request, you can use the parameters you passed in, without adding the default is callback, here I use the defaultTry{PrintWriter out=Response.getwriter (); Out.println ("Callback" + "(" +resultjson.tostring (+) + ")");//returns JSONP format data, to be wrapped in callbackOut.flush (); Out.close (); System.out.print ("1");} Catch(Exception e) {//TODO auto-generated Catch blockE.printstacktrace (); E.getmessage ();}return NULL;}
JSONP principle
JSONP cross-domain is implemented by dynamically creating a script tag for cross-domain, the src attribute of the script tag is not a cross-domain limitation, and the JSONP request is equivalent to sending our request through the SRC of the script tag, The data returned in the background is callback (name can be named when the request is sent) wrapped, the front end of the data will be called after the page callback (the function is also jquery dynamically generated functions), JSON format of the data directly into the parameter, That's why the data we're returning back in the background is callback wrapped up.
So you can request data through JSONP to a cross-domain server.
Resolving Jsonp+java instances across domains