要将表单提交返回的响应的contentType从text/html改为application/json,你可以使用以下示例代码来实现:
在服务器端,使用以下代码将响应的contentType设置为application/json:
import org.springframework.http.MediaType;
@PostMapping("/submitForm")
public ResponseEntity submitForm(@RequestBody FormObject formObject) {
// 处理表单数据
// ...
// 构造JSON响应
String jsonResponse = "{\"message\": \"Form submitted successfully.\"}";
// 设置响应的contentType为application/json
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
// 返回JSON响应
return new ResponseEntity<>(jsonResponse, headers, HttpStatus.OK);
}
在客户端,使用以下代码来接收application/json类型的响应:
fetch('/submitForm', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(formData)
})
.then(response => response.json())
.then(data => {
// 处理响应数据
console.log(data);
})
.catch(error => {
// 处理错误
console.error(error);
});
在上面的示例中,我们使用Spring Boot的@PostMapping注解来处理表单的POST请求,并将响应的contentType设置为application/json。在客户端,我们使用fetch API来发送POST请求,并使用.json()方法将响应转换为JSON格式的数据。
上一篇:表单提交返回错误的值
下一篇:表单提交返回空白页面