javascript Codeigniter 通过单击按钮更改表单操作
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11320250/
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
Codeigniter change form action by clicking buttons
提问by CyberJunkie
I have 2 submit buttons in my form and I'm trying to make each one go to a different controller method. I'm trying not avoid the use of multiple forms.
我的表单中有 2 个提交按钮,我试图让每个按钮转到不同的控制器方法。我尽量不避免使用多种形式。
I'm currently using
我目前正在使用
<button type="submit" onclick="javascript: form.action='restore'">Restore</button>
<button type="submit" onclick="javascript: form.action='delete'">Delete</button>
...which works but I'm not sure if that's the best method. Any thoughts?
...这是有效的,但我不确定这是否是最好的方法。有什么想法吗?
回答by VVLeon
Usually I'd like to handle the multiple submits by giving button/input tag a name attr. In this way you can submit and call to one function/action in one same controller, just by checking which button was submitted. e.g:
通常我想通过给按钮/输入标签一个名称属性来处理多次提交。通过这种方式,您可以在同一个控制器中提交和调用一个函数/动作,只需检查提交的是哪个按钮。例如:
<form id="your_form" action="your_controller/process" method="post">
<input type="submit" name="restore" id="restore" value="Restore" />
<input type="submit" name="delete" id="delete" value="Delete" />
</form>
Then in your controller, there will be a function called "process" doing this:
然后在您的控制器中,将有一个名为“process”的函数执行此操作:
function process(){
if(isset($_POST["restore"])) {
//do your restore code
}
if(isset($_POST["delete"])){
//do your delete code
}
}
Hope this would help.
希望这会有所帮助。
回答by Arda
Best to do is with javascript, after all it's being done after page is rendered. This is an alternative solution (sorry it's jQuery I'm not very good at vanilla JS).
最好使用 javascript,毕竟它是在页面呈现后完成的。这是一个替代解决方案(对不起,它是 jQuery,我不太擅长 vanilla JS)。
View:
看法:
<div id="submit-buttons" action="<?php echo site_url('controller/postmethod1'); ?>?"?????>Submit 1</div>
<div id="submit-buttons" action="<?php echo site_url('controller/postmethod2'); ?>">Submit 2</div>?
JS:
JS:
?$(function(){
$('.submit-buttons').click(function(){
$('form').attr('action',$(this).attr('action')).submit();
return false;
});
});?
So when after buttons were clicked, it will update the form action parameter from the action attribute of the submit button, and then submit the form right after that.
因此,当单击按钮后,它将从提交按钮的 action 属性更新表单操作参数,然后立即提交表单。
P.s: I didn't test it, but it should work.
Ps:我没有测试它,但它应该可以工作。
回答by fedejp
What about this?
那这个呢?
<?php echo form_open('controller/method',array('id'=>'my_form')); ?>
<!--Form-->
<input type="submit" value="Submit" />
<?php echo form_close();?>
Hope it helps
希望能帮助到你