gpt4 book ai didi

jquery - Jackson 无法读取文档 : Unrecognized token 'contactForm' : was expecting ('true' , 'false' 或 'null' )

转载 作者:行者123 更新时间:2023-12-01 00:05:32 24 4
gpt4 key购买 nike

我想使用 JQuery 向 Spring Controller 发送 POST 请求,但我不断从 jquery 收到此错误

Could not read document: Unrecognized token 'contactForm': was expecting ('true', 'false' or 'null')
at [Source: java.io.PushbackInputStream@38220bcd; line: 1, column: 13]; nested exception is com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'contactForm': was expecting ('true', 'false' or 'null')
at [Source: java.io.PushbackInputStream@38220bcd; line: 1, column: 13]

这是 POST 请求

$('#contactForm').on('submit', function(e){
e.preventDefault();
var contactForm = new Object;
var firstName = $('#firstName').val();
var lastName = $('#lastName').val();
var email = $('#email').val();
var message = $('#message').val();
contactForm.firstName = firstName;
contactForm.lastName = lastName;
contactForm.email = email;
contactForm.message = message;
contactForm.accepted = true;
console.log(JSON.stringify(contactForm));
$.ajax({
type: 'POST',
url: '/checkContact.json',
contentType : 'application/json; charset=utf-8',
dataType: 'json',
data: {
contactForm: JSON.stringify(contactForm)

},
success: function(response){
console.log(response)
$('#success').text(response.message);
},
error: function(data){
console.log(data.responseJSON.message);
}
})
})

这是 Controller

 @PostMapping("/checkContact.json")
public @ResponseBody String sendContactForm(@Valid @RequestBody ContactForm contactForm, BindingResult result, HttpServletRequest request) throws MalformedURLException, JsonProcessingException{

//logic here

}

和联系表格

public class ContactForm {

@NotNull
@NotEmpty
@ValidEmail
private String email;

@NotNull
@NotEmpty
private String firstName;

@NotNull
@NotEmpty
private String lastName;

@NotNull
@NotEmpty
private String message;

// @AssertTrue
private boolean accepted;

//getters and setters
}

我不知道到底发生了什么,因为例如,如果我尝试使用带有此正文的 POSTMAN 向 Controller 发送 JSON,这与 JSON.stringify(contactForm),一切都很顺利,所以 jackson 在幕后做了一些奇怪的事情......

{
"fistName": "John",
"lastName": "Smith",
"email": "a@a.aa",
"message": "Hello"
"accepted":true
}

最佳答案

在您的 jQuery ajax 调用中调整您的数据值:

    $.ajax({
type: 'POST',
url: '/checkContact.json',
contentType : 'application/json; charset=utf-8',
dataType: 'json',
data: JSON.stringify(contactForm),
success: function(response){
console.log(response)
$('#success').text(response.message);
},
error: function(data){
console.log(data.responseJSON.message);
}
})

发生的事情是 jQuery 正在将您的对象转换为查询参数字符串并发送它。这看起来像:

contactForm=%7B%22fistName%22%3A%22John%22%2C%...

Jackson 尝试将查询参数解释为失败的请求正文。

这可以通过查看浏览器中的网络选项卡并查看请求正文来确认

关于jquery - Jackson 无法读取文档 : Unrecognized token 'contactForm' : was expecting ('true' , 'false' 或 'null' ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47818687/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com