Big data learning_Spring transfer Json object string

1 Introduction

1.1 Demand

  I wrote an ajax request again, and the background always received null. The cause of the problem was that the Json format was not clear. This article will be sorted out.
  The requirements of this block are as follows:
  realize that the web page sends a character in the page input tag to the back-end control layer based on an ajax request, the control layer returns an object to the front-end after receiving the data call method, and the front-end executes business response after receiving the object.


Front end acquisition interface


Insert picture description here


Insert picture description here


1.2 Realization

  Paste the success code:

// 1.前端为input绑定一个change事件函数,内容改变时发送POST类型的ajax请求
<script>
        $("#dep_id").change(function () {
    
    
            var dep_id = $("#dep_id").val();
            let url = '${pageContext.request.contextPath}/department/findById';
            $.ajax({
    
    
                type: 'POST',
                url: url,
                data:{
    
    "dep_id":dep_id},    
                dataType : "json",
                //成功响应的结果
                success : function (resp) {
    
    ...}                              
            })
        })
    </script>
// 2.后端接收dep_id并调用业务层方法
// 这里是基于id属性对数据库进行查询,返回查询到的department
@Controller
@RequestMapping("/department")
public class DepartmentController {
    
    

    @Autowired
    private DepartmentService departmentService;

    @RequestMapping("/findById")
    @ResponseBody
    public Department findById(Integer dep_id) {
    
    
        //System.out.println(dep_id);
        Department department = departmentService.findById(dep_id);
        if(null==department){
    
    
            department = new Department();
        }
        return department;
    }
}

2. Json format in Ajax send request

  Let’s first review Ajax: Ajax stands for "Asynchronous Javascript And XML" (asynchronous JavaScript and XML), which refers to a web development technology for creating interactive web applications. That is, the technology of some web pages can be updated without reloading the entire web page. Through a small amount of data exchange with the server in the background, the web page can be updated asynchronously.

2.1 Ajax after jQuery package

  jQuery encapsulates the native ajax of js. The encapsulated ajax operation method is more concise and more powerful. The jquery methods related to ajax operation are:

Request method grammar
GET request $.get(url, [data], [callback], [type])
POST request $.post(url, [data], [callback], [type])
AJAX request $.ajax([settings])

  Common attributes of AJAX requests:

Attribute name Explanation
url The requested server-side url address
async (Default: true) All requests are asynchronous by default. To send a synchronization request, set to false
data The data sent to the server can be in the form of key-value pairs or js objects
type (Default: "GET") Request method ("POST" or "GET")
contentType The type of content used when sending data to the server. The default is: "application/x-www-form-urlencoded"
dataType The expected return data type, the value can be xml, html, script, json, text, _defaul, etc.
success Callback function after successful request
error Call this function when the request fails

The contentType is particularly important here:

<script>
        $("#btn1").click(function () {
    
    
            let url = '${pageContext.request.contextPath}/user/ajaxRequest';
            let data = {
    
    "id":1,"username":"张三"};
            $.ajax({
    
    
                type: 'POST',
                url: url,
                data : data,
                //contentType : 'application/json;charset=utf-8',
                success: function (resp) {
    
    
                    alert(JSON.stringify(resp));
                }
            })
        })
</script>
  • When the contentType is not specified and the default value is used:
    Insert picture description here
      At this time, the request body data is submitted in the form of standard Form Data, and multiple data are spliced ​​with ampersands, and the parameter format is key1=value1&key2=value2&...
    In this case, it is mostly used for simple transmission Data, based on ssm development, the background can receive the data directly, without adding @RequestBody before the formal parameters.
      For example, transmitting data = {"id":1,"username":"Zhang San"}; the background can use the formal parameter int id (at this time the formal parameter name must be equal to the key name of the parameter to be received) to receive the id in the data Value; secondly, you can also use entity class objects to receive the entire data, such as User user (the User class must have id and username attributes, the class must provide the key value get/set method), here it seems that mvc is still based on the get/set method To encapsulate the received data into a class object, if there are other properties in the class, it will be automatically set to the default value.

  • When contentType: "application/json;charset=UTF-8" is specified:
    Insert picture description here
      if contentType is set, the request body data is submitted in the form of Request Payload, and the ssm background must use the @RequestBody annotation before the formal parameter type instead of the annotation background There is no way to encapsulate the entity, it will return all objects with null properties.
    Note: JSON parse error: Unrecognized token'xx'
      may be reported here . At this time, it means that the format of the passed parameter is incorrect. It can be solved by data: JSON.stringify(data). The internal process is to use JSON.stringify to serialize the js object (JSON string), and then use JSON.parse to deserialize (restore) the js object.   If JSON parse error: Cannot deserialize instance of… is reported , it means that the receiving class does not support deserialization, and it must not be a pojo class, so you need to modify the receiving class.

Guess you like

Origin blog.csdn.net/qq_41612830/article/details/112465969