415不支持的媒体类型从jquery转换json

sdnqo3pr  于 2021-07-14  发布在  Java
关注(0)|答案(0)|浏览(200)

在spring应用程序中使用json时遇到问题:
服务器拒绝了此请求,因为请求实体的格式不受请求方法的请求资源的支持。
jsp文件中的脚本:

<script>
    $(document).ready(function () {
        $('[id^=input]').attr('value', 1)
        $('button').click(function () {
            let id = $(this).attr('id')
            let input = $('#input' + id).prop('value')
            $.ajax({
                type: 'POST',
                url: '${pageContext.servletContext.contextPath}/cart',
                contentType : 'application/json',
                data: JSON.stringify({
                    phoneId: id,
                    quantity: input
                }),
                success: function (msg) {
                    console.log(msg)
                    $('[id^=message]').attr('hidden', true)
                    let message = $('#message' + id)
                    message.attr('class', 'alert alert-success')
                    message.attr('value', msg)
                    message.attr('hidden', 'false')
                    $('#input' + id).attr(value, '1');
                },
                error: function (msg) {
                    console.log("error")
                    console.log(msg)
                    $('[id^=message]').attr('hidden', true)
                    let message = $('#message' + id)
                    message.attr('class', 'alert alert-danger')
                    message.attr('value', msg)
                    message.attr('hidden', 'false')
                }
            })
        })
    })
</script>

控制器

@Controller
@RequestMapping(value = "/cart")
public class CartController {
    private static final String ADDED_TO_CART = "Added to cart successfully";
    @RequestMapping(method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public ResponseEntity<String> addPhone(@RequestBody CartItemForm cartItemForm, BindingResult bindingResult) {
        // some code
        return ResponseEntity.ok(ADDED_TO_CART);
    }

cartitemform公司

public class CartItemForm {
    private String phoneId;
    private String quantity;
    // getters and setters
}

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题