The perfect solution of Ajax Cross-domain query
This article introduces the knowledge of "the perfect solution to Ajax cross-domain query". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Reason: browser security restrictions prohibit ajax from obtaining data across domains.
Solution: data in JSON format can be obtained across domains through the $. GetJSON () provided by jquery. Advantages: strong compatibility.
Java background code:
The copy code is as follows:
Protected void doPost (HttpServletRequest req, HttpServletResponse resp)
Throws ServletException, IOException {
String callback = req.getParameter ("callback"); / / the custom function name generated by jquery
Resp.setCharacterEncoding ("UTF-8")
Resp.setContentType ("text/html;charset=utf-8")
PrintWriter out = resp.getWriter ()
/ / returns a string in json format. Note that the output to the foreground must be in callback (string in json format)
/ / callback is the custom function name generated by jquery. If this format is returned, the foreground jquery code will automatically replace it.
/ / callback function is a callback function, thus achieving cross-domain effect. There are other cross-domain solutions on the Internet, such as AJAJ.
/ / the principle should be the same as this method. The disadvantages are: the amount of data returned should not be too large, the security is poor, and important data is not recommended.
/ / to be transmitted in this form.
Out.print (callback+ "({name:'111',sex:'222'});")
Out.flush ()
Out.close ()
}
Js foreground call code:
The copy code is as follows:
$(function () {)
/ / parameters that need to be passed may not be passed.
Var data= {param1: "param1", param2: "param2"}
/ / Note that url must be callback=? The callback parameter name can be customized
/ / but the backend must also synchronize the obtained parameter name
Var url = 'http://192.168.1.216:8080/DSFA/getUser?callback=?';
$.getJSON (url,data,function (backdata) {
/ / in fact, the function returned by the backend has been replaced with this function, so backdata
/ / it is the json object that you passed from the background.
Alert (backdata)
});
})
This is the end of the content of "perfect solution to Ajax Cross-domain query". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!