Отдельные кнопки отправки в формах, которые сообщают «действию» формы для публикации в разные файлы? - PullRequest
1 голос
/ 19 декабря 2011

Я добавил в форму дополнительную кнопку «Отправить», которую я собираюсь использовать следующим образом.

  1. Пользователь выбирает элемент
  2. Пользователь нажимает «Добавить еще один элемент» кнопку «Отправить» в форме.
  3. Форма ПОСТАВЛЯЕТСЯ перед собой и перезагружает страницу, чтобы пользователь мог добавить еще один элемент
  4. Как только пользователь добавил несколько элементов, пользователь нажимает кнопку «Завершено».
  5. Форма отправляет в другой файл все накопленные элементы.

У меня неприятное ощущение, что это может быть недостижимо только с помощью PHP / HTML и что мне, возможно, придется использовать некоторый Javascript для изменения действия формы, прежде чем форма начнет отправлять данные POST?

Мысли и идеи?

Спасибо

Ответы [ 3 ]

3 голосов
/ 19 декабря 2011

Дайте двум кнопкам отправки одинаковые имена, но разные значения. Вы можете проверить значение в вашем php-файле.

Пример

<form action="something.php" method="post">
<input type="submit" name="submit" value="one">
<input type="submit" name="submit" value="two">
</form>

something.php

switch( $_POST['submit'] ) {
    case 'one':
    case 'two':
}
2 голосов
/ 19 декабря 2011

Вы можете использовать JavaScript для изменения формы в зависимости от того, какая кнопка нажата, или вы можете проверить на стороне сервера (то есть, используя PHP), какая кнопка была нажата, и действовать соответственно.

Кнопка отправки - это ввод формы, как и любой другой, т. Е. Вы можете дать ему имя и значение, которое вы можете проверить на стороне сервера.

На стороне клиента (т. Е. С помощью JavaScript) вы привязываете обработчик к событию click кнопки, изменяете атрибут действия формы и отправляете его по новому адресу.

Вот пример на стороне клиента:

<!doctype html>
<html>
    <head>
        <title>Form submit test</title>
    </head>
    <body>
        <form action="baz.html" method="post">
            <input id="bar" type="submit" class="button" value="bar.html" name="" />
            <input id="foo" type="submit" class="button" value="foo.html" name="" />
        </form>

        <script>
            // Find the two buttons from the DOM and assign them to separate variables
            var barBtn = document.getElementById('bar'),
                fooBtn = document.getElementById('foo');

            // Click-handler for the buttons. 
            // NB! For this code to work as intended, it needs to run 
            // in the context of the button, otherwise, the this-keyword 
            // will not resolve correctly and this will result in an error
            // NB2! This code also requires that a button's value will be
            // the desired action handler. Usually you would probably not
            // do this, but use the button's name/value to lookup the 
            // correct form action.
            function modifyAction(e) {
                this.form.action = this.value;
            }

            // Bind an event handler to an object
            // NB! This is not code you should use in production
            function bindEvent(target, event, callback) {
                if (target.addEventListener) {
                    target.addEventListener(event, callback, false);
                } else if (target.attachEvent) {
                    target.attachEvent('on' + event, callback);
                }
            }

            // Delegate creates a wrapping closure which binds the 
            // original function's context to an object, i.e. ensuring
            // the this-keyword always refers to the same object when
            // the returned function is invoked. 
            function delegate(context, method) {
                return function () {
                    return method.apply(context, arguments);
                }
            }

            // Bind the click-event of the barBtb, and handle it
            // with the modifyAction-function bound to the barBtn.
            // I.e. run the modifyAction function, with the this-keyword
            // bound to barBtn
            bindEvent(barBtn, 'click', delegate(barBtn, modifyAction));

            // Same as above for fooBtn
            bindEvent(fooBtn, 'click', delegate(fooBtn, modifyAction));
        </script>
    </body>
</html>

Просто для полноты, вот пример того же jQuery:

<form action="baz.html" method="post">
    <input id="bar" type="submit" class="button" value="bar.html" name="" />
    <input id="foo" type="submit" class="button" value="foo.html" name="" />
</form>

<script>
// Jquery event-handlers are automatically bound to
// the element selected, so using "this" is safe
function modifyAction(e) {
    this.form.action = this.value;
}

// Bind the click-event on all input with type=submit
$("input[type=submit]").click(modifyAction);
</script>
2 голосов
/ 19 декабря 2011

Вы можете сделать это без JavaScript. Просто дайте названия кнопок отправки с разными значениями:

<button type="submit" name="btn" value="addItem">Add item</button>
<button type="submit" name="btn" value="finish">Finished</button>

Теперь внутри сценария, который вы отправляете, вы можете определить, какая кнопка была нажата, изучив значение $_POST['btn'] и выполнить соответствующие действия.

...