Cause:Browser security restrictions are imposed to prevent cross-origin ajax data acquisition.
Solution:$. GetJSON () provided by jquery can be used to obtain JSON-format data across domains. Advantage: strong compatibility.
Java background code:
Copy codeThe Code is as follows:
Protected void doPost (HttpServletRequest req, HttpServletResponse resp)
Throws ServletException, IOException {
String callback = req. getParameter ("callback"); // UDF name generated by jquery
Resp. setCharacterEncoding ("UTF-8 ");
Resp. setContentType ("text/html; charset = UTF-8 ");
PrintWriter out = resp. getWriter ();
// Return a json string. Note that the format output to the foreground must be callback (A json string );
// Callback is the custom function name generated by jquery. If this format is returned, the jquery code in the foreground will be automatically replaced.
// The callback function is called the callback function to achieve cross-origin effect. There are other cross-origin solutions on the Internet, such as AJAJ.
// The principle should be the same as this method. Disadvantage: The returned data volume should not be too large, and the security is poor. We recommend that you do not use important data.
// It must be passed in this form.
Out. print (callback + "({name: '000000', sex: '000000 '});");
Out. flush ();
Out. close ();
}
Js front-end call code:
Copy codeThe Code is as follows:
$ (Function (){
// The parameter to be passed. You can skip this parameter.
Var data = {param1: "param1", param2: "param2 "};
// Note that the url must use callback =? Callback parameter names can be customized,
// The parameter name that must be obtained simultaneously in the background
Var url = 'HTTP: // 192.168.1.216: 8080/DSFA/getUser? Callback =? ';
$. GetJSON (url, data, function (backdata ){
// In fact, the function returned by the background has been replaced by this function, so backdata
// It is the json object that you pass from the background.
Alert (backdata );
});
})
If you have any questions, leave a message ....