Home  >  Article  >  Web Front-end  >  Ajax front-end and back-end cross-domain request processing methods

Ajax front-end and back-end cross-domain request processing methods

小云云
小云云Original
2018-02-09 09:46:131553browse

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 called. The external interface (interface to other engineering projects) is completed. This article mainly introduces the front-end cross-domain request processing and back-end cross-domain data processing methods, and analyzes the cross-domain issues of Ajax in detail.

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. Processing cross-domain requests in the background

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){ 
  Map<String,Object>map=new HashMap<String, Object>(); 
  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是&#39;1&#39;,则查询第一级目录内容 
    map.put("results", this.carBrandService.findByAttr(null, "first_letter asc")); //调用查询方法,结果放入map 
  } else if ("2".equals(level)) {          //如果level是&#39;2&#39;,则查询第二级目录内容 
    map.put("results", this.carSerieService.findByAttr("parent_id="+id, "first_letter asc"));//调用查询方法,结果放入map 
  } else if ("3".equals(level)) {          //如果level是&#39;3&#39;,则查询第三极目录内容 
    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)+")"); 
}

2. Front-end ajax cross-domain request data

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:&#39;http://192.168.1.106:8086/carBrand/json.html?level=&#39;+level+&#39;&id=&#39;+id+&#39;&callback=?&#39;,   //将callback写在请求url后面作为参数携带 
    type:&#39;GET&#39;, 
    async:false, 
    dataType:&#39;jsonp&#39;, 
    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:&#39;http://192.168.1.106:8086/carBrand/json.html?level=&#39;+level+&#39;&id=&#39;+id, 
    type:&#39;GET&#39;, 
    dataType:&#39;jsonp&#39;, 
    jsonp: &#39;callback&#39;,          //将callback写在jsonp里作为参数连同请求一起发送 
    jsonpCallback:&#39;jsonpCallback1&#39;,    
    success:function(data){            
    console.log(data);       
}); }

The above two ways of writing have the same meaning, but they are written in different ways.

Next, I will add the working principle of jsonp.

3. Analysis of the cross-domain principle of jsonp

The most basic principle of jsonp is: dynamically add a 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag, and the src attribute of the script tag is not cross-domain of restrictions. In this way, this cross-domain method has nothing to do with the ajax XmlHttpRequest protocol.

JSONP is an unofficial protocol that allows Script tags to be integrated on the server side and returned to the client through javascript callback The form implements cross-domain access to JSONP, that is, JSON with Padding. Due to the restrictions of the same-origin policy, XmlHttpRequest is only allowed to request resources from the current source (domain name, protocol, port). If we want to make a cross-domain request, we can make a cross-domain request by using the script tag of html and return the script code to be executed in the response, where the javascript object can be passed directly using JSON. This cross-domain communication method is called JSONP.

jsonCallback function jsonp1236827957501(....): It is registered by the browser client. After obtaining the json data on the cross-domain server, the callback function

Jsonp principle:

First register a callback (such as: 'jsoncallback') on the client, and then pass the callback name (such as: jsonp1236827957501) to the server. Note: After the server gets the callback value, it must use jsonp1236827957501(...) to include the json content to be output. At this time, the json data generated by the server can be correctly received by the client.

Then use javascript syntax to generate a function. The function name is the value jsonp1236827957501 of the passed parameter 'jsoncallback'.

Finally, place the json data directly as an input parameter. function, this generates a js syntax document and returns it to the client.

The client browser parses the script tag and executes the returned javascript document. At this time, the javascript document data is passed as a parameter to the callback function predefined by the client (such as jquery in the above example) The $.ajax() method encapsulates the success: function (json)). (Dynamic execution callback function)

It can be said that the jsonp method is in principle the same as 829f4515d45765547710de74af22eea82cacc6d41bbb37262a98f745aa00fbf0 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.

Note that jquey does not support cross-domain post methods.

Related recommendations:

Vue uses axios to request data across domains in detail

Native JS implements ajax and ajax cross-domain requests

Examples explain the principle of Ajax cross-domain requests


The above is the detailed content of Ajax front-end and back-end cross-domain request processing methods. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn