Ajax cross domain query is perfectly solved through $. Getjson()

Time:2021-9-16

reason:Browser security is restricted to prohibit Ajax from obtaining data across domains.
resolvent:Data in JSON format can be obtained across domains through $. Getjson () provided by jQuery. Advantages: 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”);// Custom function name generated by jquery
resp.setCharacterEncoding(“UTF-8”);
resp.setContentType(“text/html;charset=utf-8”);
PrintWriter out = resp.getWriter();
//Return JSON format string. Note that the format output to the front station must be callback (JSON format string);
//Callback is the custom function name generated by jQuery. If this format is returned, the foreground jQuery code will automatically replace it
//The callback function is the callback function to achieve the cross domain effect. There are other cross domain schemes on the Internet, such as Ajax
//The principle should be the same as this method. The disadvantages are: the amount of returned data should not be too large and the security is poor. It is recommended that important data should not be returned
//To be passed in this form.
out.print(callback+”({name:’111′,sex:’222′});”);
out.flush();
out.close();
}

JS foreground calling code:

Copy codeThe code is as follows:
$(function(){
//Parameters that need to be transferred can not be transferred.
var data= {param1:”param1″,param2:”param2″};
//Note that the URL must be marked with callback =? The callback parameter name can be customized,
//But the background must also synchronize the parameter names obtained
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
//It’s the JSON object you passed from the background.
alert(backdata);
});
})

If you don’t understand, please leave a message