One form two action

情到浓时终转凉″ 提交于 2020-01-16 05:36:06

问题


Hi i have a few form fields i want the on click of button a the control to be sent to action 1 but on click of button 2 it has to be sent to action 2. Currently i am using js to change the form action dynamically on click. but is there any other solution. I cant do the checking after submit in a same method thet have to be two different methods.

The 2 buttons in this case are view(html data needs to be displayed) and download(same data as csv file). I am using cakephp 1.2 but i feel this is more of a generic problem


回答1:


One form can only have one action. This is a limitation of HTML. To work around it on the client-side, you need Javascript.

It sounds like the better idea would be to give each submit button a distinctive name and value. This will be submitted like other form elements, so you can detect in the Controller which button was clicked. From there it should only be a matter of switching some View logic in the controller between normal output and download.




回答2:


I found out there are few solutions

  1. Regular JavaScript to change th form action on click of the buttons
  2. AJAX to send the data to two separate actions on click of separate buttons
  3. As suggested by deceze to do the processing on server side(which was not easily possible in my case)



回答3:


HTML5 has a formaction attribute for this

<form action="/url" id="myForm">
     <input type="submit" value="save1" formAction="/url1" />
     <input type="submit" value="save2" formAction="/url2" />
</form>

Here is a fallback if you need it.

if (!('formAction' in document.createElement('input'))){
 $('form').on('click', 'input[type=submit]', function (e) {
    var attr = this.getAttribute('formAction');

    if (attr) {
        this.action = attr; //Set the form's action to formAction
    }
  });
}


来源:https://stackoverflow.com/questions/3810124/one-form-two-action

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!