简体   繁体   English

FormData 不包含按钮 Javascript

[英]FormData doesn't include the button Javascript

I'm having a problem with FormData , it was working a couple days ago but now it doesn't work, it submits all the inputs except the submit button.我在使用FormData遇到问题,几天前它正在工作,但现在不起作用,它提交了除提交按钮之外的所有输入。 Here's my login form.这是我的登录表单。

<form action="" method="post" name="login_user">
    <label for="username">Username/e-mail <span class="error" id="user-error"></span></label>
    <input type="text" name="username" id="username" required>
    <br>
    <label for="passwd">Password <span class="error" id="passwd-error"></span></label>
    <input type="password" name="passwd" id="passwd" required>
    <br>
    <p><input type="checkbox" checked name="remember"> Remember me <span class="forgot"><a href="<?php echo SITE_URL; ?>/reset">Forgotten password</a></span> </p>
    <input type="submit" id="login" value="Login" name="login">
    <p>Don't have an account? <a href="<?php echo SITE_URL; ?>/register/">Sign up</a></p>
</form>

JS for login, uses MVC. JS登录,使用MVC。

//ajax login
var login = document.forms.namedItem('login_user');
if (login) {
    login.addEventListener('submit', function (e) {
        if (validatePassword('passwd', 'passwd-error')) {
            var data = new FormData(login);
            var userlogin = new XMLHttpRequest();
            var btn = document.getElementById('login');
            btn.value = 'Login, Please wait...';

            userlogin.open('POST', url + 'login/login_user_ajax', true);
            userlogin.onload = function (event) {
                if (userlogin.status == 200) {
                    var result = JSON.parse(userlogin.responseText);
                    if (result.results == 'success.') {
                        alert('logged in'); //change this later
                    } else {
                        document.getElementById('cred-error').innerHTML = result.results;
                    }
                    btn.value = 'Login';
                }
            };
            userlogin.send(data);
        }
        e.preventDefault();
    }, false);

The login method in my controller, the button is not detected.我的控制器中的登录方法,未检测到按钮。

public function login_user_ajax() {
    $this->login_user(1);
}

private function login_user($ajax  = '')
{
    if (filter_has_var(INPUT_POST, 'login')) {
        $new_user = $this->model('User');
        $new_user->setDb(Controller::getDb());
        $new_user->set_site(SITE_URL);
        $user = trim(filter_input(INPUT_POST, 'username', FILTER_SANITIZE_STRING));
        $passwd = trim(filter_input(INPUT_POST, 'passwd', FILTER_SANITIZE_STRING));
        if ($new_user->login($user, $passwd)) {
            if ($ajax) {
                $site_data['results'] = 'success.';
                echo json_encode($site_data);
                return true;
            }else {
                $this->redirect(SITE_URL . '/edit');
            }
        } else {
            if (!$ajax){
            return 'The username or password is incorrect.';
            }else {
                $site_data['results'] = 'The username or password is incorrect.';
                echo json_encode($site_data);
                return false;
            }
        }
    }else {
        print_r($_POST);
    }
}

I get this when I print_r $_POST , with no button.当我没有按钮print_r $_POST ,我得到了这个。

在此处输入图片说明

Because you're not actually using the default submit (instead you're doing ajax), you need to add the clicked button yourself.因为您实际上并未使用默认提交(而是使用 ajax),所以您需要自己添加单击的按钮。 One easy way to do this is to add a hidden input to your form with the name you want the button to have, and then have all the buttons in the form use this click handler:一种简单的方法是使用您希望按钮具有的名称向表单添加一个隐藏输入,然后让表单中的所有按钮使用此单击处理程序:

function clickHandler() {
    this.form.theHiddenInput.value = this.value;
}

That way, if a button was used to submit the form, the button's handler sets the value of the hidden input prior to the submit .这样,如果使用按钮提交表单,则按钮的处理程序会在submit之前设置隐藏输入的值。

I had a similar problem with my SwitchToggle component that I built with a <button> element.我使用<button>元素构建的 SwitchToggle 组件也有类似的问题。 Even if the element had a name it wasn't included in my FormData when submitting the form.即使该元素有一个name它在提交表单时也不包含在我的FormData

I ended up adding a visually hidden <input type="checkbox"> in the markup with the same name and value property as the SwitchToggle component.我最终在标记中添加了一个视觉隐藏的<input type="checkbox"> ,其namevalue属性与 SwitchToggle 组件相同。 This input does nothing (it is not clickable and not visual) except showing up in FormData .除了显示在FormData之外,此输入什么都不做(它不可点击且不可见)。 This example is in React but the approach is applicable to all frameworks or vanilla JavaScript.此示例在 React 中,但该方法适用于所有框架或普通 JavaScript。

const SwitchToggle = (props) => {
  const { id, name, className } = props;
  const [enabled, setIsEnabled] = React.useState(props.enabled);

  return (
    <>
      <input
        style={{opacity: 0.05}}
        name={name}
        checked={enabled}
        type={"checkbox"}
      />
      <button
        className={`switch-toggle ${enabled ? 'on' : 'off'}`}
        onClick={(e) => {
          e.preventDefault();
          setIsEnabled(!enabled);
        }}
      />
    </>
  );
};

Full example on Codepen . Codepen 上的完整示例

Since my component is On/Off I used a checkbox input but you might as well use a text input with a string value.由于我的组件是开/关,我使用了复选框输入,但您也可以使用带有字符串值的文本输入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM