如何在ajax调用中调用e.preventDefault()?

时间:2018-02-27 09:09:29

标签: javascript ajax reactjs

当用户点击表单的提交按钮时,会调用handleSubmit。所以,我想在我的ajax调用中正确调用e.preventDefault(),由于ajax的异步性质,这是不可能的。我该如何解决这个问题?

class FormRegister extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            username: '',
            email: '',
        }

        this.handleSubmit = this.handleSubmit.bind(this);
    }

    handleSubmit(e) {
        // some code here

        // Check for username or email already exists
        $.ajax({
            type: 'POST',
            url: '/api/checkEmailUsername',
            data: {
                username: this.state.username,
                email: this.state.email
            }
        }).then(function(incomingJSON) {
            console.log('incomingJSON:', incomingJSON);
            if (incomingJSON.error) {
                e.preventDefault();
            }
        }
    });
}

1 个答案:

答案 0 :(得分:0)

您使用的方法是异步的。这意味着您需要稍微改变处理事物的方式。在异步代码之前移动e.preventDefault()调用,如下所示。

此代码假设您有一个form元素,其引用名称为form

class FormRegister extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      username: '',
      email: '',
    }

    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(e) {
    e.preventDefault();

    $.ajax({
      type: 'POST',
      url: '/api/checkEmailUsername',
      data: {
        username: this.state.username,
        email: this.state.email
      }
    }).then(function(incomingJSON) {
      console.log('incomingJSON:', incomingJSON);
      if (incomingJSON.error) {
        // Handle errors here.
        return;
      }

      // Submit the form.
      this.refs.form.submit();
    });
  }
}