gpt4 book ai didi

java - JQuery、AJAX、POST请求、参数丢失

转载 作者:行者123 更新时间:2023-12-01 06:16:03 26 4
gpt4 key购买 nike

我的 Web 应用程序基于 Spring MVC (4.0.5)。我正在尝试使用 jQuery (v. 2.1.1) 通过 AJAX 发送 POST 请求:

function deleteItem(id) {
alert("Deleting " + id);
$.ajax({
url: "ajax/delete_item",
type: 'POST',
dataType: 'html',
data: {"id": id},
contentType: 'application/json',
mimeType: 'application/json',
success: function(data) {
var txt = data;
$('#message').html(txt);
},
error: function(data, status, err) {
$('#message').html(err);
}
});
}

Controller的方法调用成功但请求中没有参数:

@RequestMapping(value = "/ajax/delete_item", method = RequestMethod.POST)
public @ResponseBody String ajaxDelete(HttpServletRequest request) {
Enumeration<String> en = request.getParameterNames();
while (en.hasMoreElements()) {
String pname = en.nextElement();
System.out.println("//// " + pname); // just for test
}
String idStr = request.getParameter("id");
Integer id = Integer.parseInt(idStr);
//...

为什么请求参数丢失?不仅仅是值,参数本身也丢失了。这里出了什么问题?

最佳答案

如果您要从 ajax 传递内容类型 contentType: 'application/json',则在 Spring 方法声明中添加该设置,如下所示:( add Produces =定义中的“application/json”)

  @RequestMapping(value = "/ajax/delete_item", method = RequestMethod.POST , produces = "application/json")
public @ResponseBody String ajaxDelete(HttpServletRequest request) {

还有一个警告,

您提到了数据类型和mimeType,但它们并不统一。

mimeType: 'application/json' 应使用 dataType: 'json' 编写,而不是 html

关于java - JQuery、AJAX、POST请求、参数丢失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24495102/

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