ajax passes array through post method

Ajax is often used in web project development. Usually when we transfer data, one parameter name corresponds to one parameter value. The backend can get the parameters through the parameter name, so as to perform related logic processing, but sometimes we encounter For batch operations, such as deleting a list in batches, what we pass is an array of IDs. At this time, the front and back ends need to do some special processing for the array transfer. Here are two ways to handle the problem of passing array parameters in ajax post requests.

  • When specifying parameter serialization through an ajax attribute traditional:true, no deep serialization is performed.
  • The parameters are passed to the backend as an array through JSON.stringify(). The backend cannot obtain the parameters by getting the parameter name, and needs to read the parameters through the inputstream stream.

The first way: add ajax request parameters traditional

Front-end code:

Backend code (springmvc):

In the parameter form-data we pass in this way, each parameter has a parameter name during the transmission process, here it is called ids. If the traditional: true setting is not set, the parameter name is added after ids in the parameter transmission. [], the server cannot get parameters by parameter name:

 

After setting traditional:true, the parameter becomes like this:

In this method of parameter passing, the backend can directly obtain the parameter value through the parameter name ids, and the obtained parameter is also an array.

The second way: Pass an array through the body, the parameter has no name, and the backend needs to read it through the stream.

Front-end code:

Backend code (springmvc):

In this way form-data looks like this:

The parameter has no name, and the backend needs to read the data in the body through the input stream. One thing to note here is that if there are other parameters, the parameters in the body must be obtained before other parameters are obtained. Otherwise, once request.getParameter() is passed, the parameters in the body will be invalid.

Guess you like

Origin blog.csdn.net/feinifi/article/details/81180673