Reason:Restrictions on browser security prohibit Ajax from acquiring data across domains.
Workaround:The $.getjson () provided through jquery can get data in JSON format across domains. Advantages: Strong compatibility.
Java background code:
Copy Code code as follows:
protected void DoPost (HttpServletRequest req, HttpServletResponse resp)
Throws Servletexception, IOException {
String callback =req.getparameter ("callback");//jquery generated Custom function name
Resp.setcharacterencoding ("UTF-8");
Resp.setcontenttype ("Text/html;charset=utf-8");
PrintWriter out = Resp.getwriter ();
Returns the JSON format string, noting that the format to be exported to the foreground must be callback (a JSON-formatted string);
Callback is the name of the custom function generated by jquery, which returns the foreground jquery code automatically replacing
The callback function achieves Cross-domain effects for this callback function, and there are other Cross-domain scenarios on the web such as: Ajaj
The principle should be the same as this method. The disadvantage is: the amount of data returned should not be too large, poor security, the proposed important data does not
To pass through this form.
Out.print ({name: ' callback+ ', Sex: ' 222 '});
Out.flush ();
Out.close ();
}
JS Front call code:
Copy Code code as follows:
$ (function () {
The parameters that need to be passed are not transmitted.
var data= {param1: "param1", param2: "Param2"};
Note that the URL must be callback= in the form of a concatenation, callback parameter names can be customized,
But the background must also be synchronized to get the parameter names
var url = ' http://192.168.1.216:8080/DSFA/getUser?callback=? ';
$.getjson (Url,data,function (backdata) {
In fact, the function returned in the background has been replaced with this function, so backdata
Is the JSON object that you passed back from the background.
alert (backdata);
});
})
If you do not understand the place, please leave a message ....