This article introduces the front-end cross-domain request processing and the back-end cross-domain data processing methods, and analyzes the cross-domain issues of ajax in detail. Friends who need this can learn from it.
I have been working on the front-end development of public accounts recently, and encountered the problem of Ajax cross-domain requests, such as the three-level linkage of province-city-county in the region, the three-level linkage query of car brand-car series-car model, etc. All need to be completed by calling external interfaces (interfaces of other engineering projects). Now I will share my personal solution to cross-domain requests. Of course, with the help of the background programmer, I figured out the origin of it. I quickly recorded it and accumulated it slowly. I hope it can be helpful to everyone. Please also Actively provide comments or suggestions.
Cross-domain requests need to use the background code to receive the callback function and further process the json data; the frontend then uses an ajax request to send the callback parameters to the server and specify the data format as jsonp.
1.CarBrandController.java (car brand interface java file), the methods listed here are mainly used to query the corresponding according to different level values Brand, car series, car model. Here, a callback function is processed for cross-domain requests. If the returned callback is null, it is not a cross-domain request. No special processing is required. Just print the json interface data directly; if If the returned callback is not null, it indicates a cross-domain request. In this case, special processing is required for the json data, that is, a pair of parentheses are added to the outer layer of the json data. For details, please see the printlnJSONObject method in the HttpAdapter.java file. .
public void json(HttpServletRequest request,HttpServletResponse response){ Mapmap=new HashMap (); String id = request.getParameter("id"); //接收ajax请求带过来的id String level = request.getParameter("level"); //接收ajax请求带过来的level String callback=request.getParameter("callback"); //接收ajax请求带过来的callback参数 if ("1".equals(level)) { //如果level是'1',则查询第一级目录内容 map.put("results", this.carBrandService.findByAttr(null, "first_letter asc")); //调用查询方法,结果放入map } else if ("2".equals(level)) { //如果level是'2',则查询第二级目录内容 map.put("results", this.carSerieService.findByAttr("parent_id="+id, "first_letter asc"));//调用查询方法,结果放入map } else if ("3".equals(level)) { //如果level是'3',则查询第三极目录内容 map.put("results", this.carModelYearService.findByAttr("parent_id="+id, "jian_pin desc"));//调用查询方法,结果放入map } map.put("level",level); if (null==callback) { //如果接收的callback值为null,则是不跨域的请求,输出json对象 HttpAdapter.printlnObject(response, map); }else{ //如果接收的callback值不为null,则是跨域请求,输出跨域的json对象 HttpAdapter.printlnJSONPObject(response, map, callback); } }
2.HttpAdapter.java (output object's java file), the printlnObject method prints a normal json string; the printlnJSONObject method performs special processing on the json string.
/** * 打印对象 * @param response * @param object */ public static void printlnObject(HttpServletResponse response,Object object){ PrintWriter writer=getWriter(response); writer.println(JSON.toJSONString(object)); } /** * 打印跨域对象 * @param response * @param object */ public static void printlnJSONPObject(HttpServletResponse response,Object object,String callback){ PrintWriter writer=getWriter(response); writer.println(callback+"("+JSON.toJSONString(object)+")"); }
Writing method 1: Send a parameter callback= to the server? , and specify the dataType as 'jsonp' format. The data format specified during cross-domain requests must be in the form of jsonp.
function loadData(obj,level,id,value){ $.ajax({ url:'http://192.168.1.106:8086/carBrand/json.html?level='+level+'&id='+id+'&callback=?', //将callback写在请求url后面作为参数携带 type:'GET', async:false, dataType:'jsonp', success:function(data){ console.log(data); //其他处理(动态添加数据元素) }); }
Writing method 2: The callback does not need to be written in the url, but the jsonp parameter must be specified as 'callback' and a value should be given to the jsonpCallback parameter.
function loadData(obj,level,id,value){ $.ajax({ url:'http://192.168.1.106:8086/carBrand/json.html?level='+level+'&id='+id, type:'GET', dataType:'jsonp', jsonp: 'callback', //将callback写在jsonp里作为参数连同请求一起发送 jsonpCallback:'jsonpCallback1', success:function(data){ console.log(data); }); }
The above two ways of writing have the same meaning, but they are written in different ways.
Next, add the working principle of jsonp.
The most basic principle of jsonp is: dynamically add a are consistent (qq space uses this method to achieve cross-domain data exchange). JSONP is a script injection (Script Injection) behavior, so there are Certain security risks.
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future. Related articles:About the actual usage of log4js in Express
How to implement WebSocket function using NodeJS
How to get node elements using JS
The above is the detailed content of How to implement ajax front-end and back-end cross-domain requests. For more information, please follow other related articles on the PHP Chinese website!