Html 从没有jquery的按钮的html的onclick事件调用Spring mvc控制器的post方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37268321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call Spring mvc controller's post method from html's onclick event of button without jquery
提问by iknownothing
where i am trying to use button(not necessarily for purpose of submit) and onclick i want to call spring mvc's controller method whose requestmethod type should be POST not GET.
我试图使用按钮(不一定是为了提交)和 onclick 我想调用 spring mvc 的控制器方法,其 requestmethod 类型应该是 POST 而不是 GET。
<input type="button" onClick="location.href='/result'"/>
This is my controller method which is being called on click.
这是我的控制器方法,它在点击时被调用。
@RequestMapping(value="/result")
public ModelAndView postPrintHello(@ModelAttribute("product") Product product){
ModelAndView model = new ModelAndView();
model.addObject("product", product);
model.setViewName("result");
return model;
}
But when i Add RequestMethod.POST it is not called. Please suggest me wayout for this and also let me know if i missed something from view front.
但是当我添加 RequestMethod.POST 时它不会被调用。请为我建议出路,如果我错过了从前面看的东西,也请告诉我。
回答by Ahmad
try this
尝试这个
HTML:
HTML:
<input type='button' value='Submit'>
JS:
JS:
$('input').on('click', function () {
$.ajax({
type:'POST',
url :"result",
success: function(data) {
console.log('success',data);
},
error:function(exception){alert('Exeption:'+exception);}
});
e.preventDefault();
});
Without JS or JQuery
没有 JS 或 JQuery
<input type="button" onclick="location.href='/result'" value="Submit" >
Note: With this way you can only send GET Request, your controller should have this annotation method = RequestMethod.GET
注意:通过这种方式你只能发送 GET 请求,你的控制器应该有这个注释 method = RequestMethod.GET
and if You want POST request without Jquery use Form
如果您想要没有 Jquery 的 POST 请求,请使用 Form
<form action="/result" method="post">
<input type="submit" value="Submit" />
</form>
回答by manish
Either make button type submit or call javascript method and submit form like document.forms["myform"].submit();
要么使按钮类型提交要么调用javascript方法并提交表单,如document.forms["myform"].submit();
回答by Er Kapil Mehta
First in form tag you have required some changes
首先在表单标签中,您需要进行一些更改
<form action="/servlet" method="post">
<input type="submit" name="login" />
</form>
it will call your doPost() method
它会调用你的 doPost() 方法