Ajax request appears 415 error solution, and JSON.stringfy() function is received in the background

Add the following code to the ajax request

contentType: "application/json;charset=UTF-8",

Extension: JSON.stringify(data) in the front-end Ajax passes parameters and the back-end accepts the format

Front desk Layui submits data template

layui.use('form',function () {
    
    
    let form = layui.form;
    form.on('submit(submitInfo)',function (data) {
    
    
        $.ajax({
    
    
            url:"/addPartner",//与controller层对接
            data:JSON.stringify(data.field), //简化写法,用JSON数据传送到后端
            // data:{
    
    
            //     "username":data.username,
            //     "phone":data.phone
            // },
            dataType:"json",
            method:"POST",
            contentType: "application/json;charset=UTF-8",  //加上这行代码解决415错误
            success:function (data) {
    
    
                alert("提交成功!")
            },
            error:function (msg) {
    
    
                alert("出现错误,请联系管理员!")
                console.log(msg)
            }
        })
    })
    return false;  //加入 return false 防止重复提交请求
})

Background controller

package com.itguigu.learn.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.Map;

@Controller
public class YoungSpaceController {
    
    

	//后台接收使用Map
    @PostMapping("/addPartner")
    public String addFriend(@RequestBody Map<String,String> map){
    
    
        System.out.println(map.get("username"));
        System.out.println(map.get("phone"));
        return "youngSpace";
    }

}

Guess you like

Origin blog.csdn.net/weixin_43967679/article/details/108051102