Reason: browser security restrictions have been made to prohibit Ajax Cross-domain access to data.
Workaround: the $.getjson () provided through jquery can get JSON-formatted data 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 a callback (JSON-formatted string);
//callback is the custom function name generated by jquery, which returns the foreground jquery code automatically replacing
//Callback functions for this callback function, so as to achieve cross-domain effect, 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, security is poor, recommend important data not
//To be passed through this form.
Out.print (callback+ "({name: ' $ ', Sex: ' 222 '});";
Out.flush ();
Out.close ();
}
JS Front call code:
Copy Code code as follows:
$ (function () {
//need to pass the parameters, you can not pass.
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 name
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 by this function, so backdata
//Is the JSON object you pass from the background.
alert (backdata);
});
})
If you do not understand the place, please leave a message ....