我目前正在尝试从 JavaScript onchange 处理程序调用 ajax 请求来调用 Spring MVC 控制器。我相信我当前在视图中调用 URL 的方式是错误的,因为当触发事件并调用 url 时,我在浏览器上收到404 错误。如果我的所有设置都正确,任何人都可以发光吗?这是我的代码:
@Controller
public class DataTableController
{
@RequestMapping(value = "/table", method = RequestMethod.GET)
public String home(Model model) throws JsonGenerationException, JsonMappingException, IOException
{
List<String> gpnList = new ArrayList<GPN>();
gpnList.add("GPN-1"); gpnList.add("GPN-2"); gpnList.add("GPN-3");
model.addAttribute("gpnList", mapper.writeValueAsString(gpnList));
return "index"; //name of my view
}
@RequestMapping(value = "/getsector", method = RequestMethod.POST)
public @ResponseBody String getSector(@RequestParam("market")String market) throws JsonGenerationException, JsonMappingException, IOException
{
List<String> sectors = new ArrayList<String>();
sectors.add("Auto"); sectors.add("Industrial"); sectors.add("Analog");
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(sectors);
}
}
查询代码:
$(document).ready(function()
{
document.getElementById("markets").onchange = function()
{
var market = $("select[id='markets'").find('option:selected').text();
var filters = { "market" : market }
filters = JSON.stringify(filters);
$.ajax({
url: "/getsector",
type: "POST",
dataType : 'json',
contentType : "application/json",
data: JSON.stringify(filters),
success: function(response)
{
console.log("sucess!");
},
error: function(e){
console.log("ERROR: ", e);
}
});
}
});
我想要实现的主要目标是能够通过 ajax 调用来调用我的控制器。任何有关 Spring Controller 映射和约定的其他提示将不胜感激。提前致谢!
如果您请求信息,您应该使用GET
requests 而不是POST
.
您正在@RequestParam
与 json 有效负载混合。如果您想将过滤器作为请求参数接收,则必须使用 url,而不是 json 负载,使用以下内容:
$(document).ready(function()
{
document.getElementById("markets").onchange = function()
{
var market = $("select[id='markets'").find('option:selected').text();
$.ajax({
url: "/getsector?market="+market,
type: "GET",
success: function(response)
{
console.log("sucess!");
},
error: function(e){
console.log("ERROR: ", e);
}
});
}
});
@RequestMapping(value = "/getsector", method = RequestMethod.GET)
public @ResponseBody String getSector(@RequestParam("market")String market) throws JsonGenerationException, JsonMappingException, IOException
{
.... your logic.
}
另一方面,如果您真的想使用POST
带有 json 负载的请求,则需要@RequestBody
在控制器上使用并将 json 对象绑定到具有相同属性的 bean。
@RequestMapping(value = "/getsector", method = RequestMethod.POST)
public @ResponseBody String getSector(@RequestBody Market market) throws JsonGenerationException, JsonMappingException, IOException
{
List<String> sectors = new ArrayList<String>();
sectors.add("Auto"); sectors.add("Industrial"); sectors.add("Analog");
return sectors;
}
public class Market
{
String market;
//getter and setter...
}
请记住,您的 javascript 也是错误的,您使用了JSON.stringify
两次。
如果您使用@ResponseBody
并且 spring 配置良好,它将在返回响应时为您进行序列化,因此您不必手动执行此操作。
此代码未经测试,仅供您参考。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句