简体   繁体   English

AJAX POST Flask WTForm 不刷新页面

[英]AJAX POST Flask WTForm without refreshing the page

Good day, I have a simple web page with an email form in it.美好的一天,我有一个简单的网页,其中包含一个电子邮件表单。 I'm trying to collect the data from it and populate a database without refreshing the template.我正在尝试从中收集数据并填充数据库而不刷新模板。 Here is my code so far:到目前为止,这是我的代码:

Form:形式:

from flask_wtf import Form

class EmailForm(Form):
email = StringField('Email Address', [
    DataRequired(message='Required field'),
    Email(message='Please provide a valid email address')
])

submit = SubmitField('send')

Route:路线:

@app.route('/', methods=('GET', 'POST'))
def index():
form = EmailForm(request.form)
if request.method == 'POST' and form.validate_on_submit():
    try:
        email = Email(form.data['email'])
        db.session.add(email)
        db.session.commit()
    except IntegrityError as e:
        app.logger.info(e)

    return redirect(url_for('index'))

return render_template('index.html', form=form)

Ajax:阿贾克斯:

$(function() {
  $('#email_submit').bind('click', function() {
    $.getJSON('/', {
      email: $('input[name="email"]').val()
    });
    return false;
  });
});

Template:模板:

<form name="collectEmail" id="collectForm" method="post" action="{{ url_for('index') }}">
    {{ form.hidden_tag() }}
    {{ form.csrf_token }}
    {% if form.csrf_token.errors %}
      <div class="warning">You have submitted an invalid CSRF token</div>
    {% endif %}

    <div class="input-group">
      {{ form.email(class='form-control', placeholder='Your Email *', type='email')}}
      <p class="help-block text-danger"></p>

      <span class="input-group-btn">
        {{ form.submit(class='btn btn-primary', id='email_submit', type='submit') }}
      </span>
    </div>
</form>

The database successfully populates;数据库成功填充; but, I would like to avoid refreshing the page after submitting the form.但是,我想避免在提交表单后刷新页面。

You are not sending the request with AJAX, #email_submit is an input of type submit, not a button, so if you don't use preventDefault() you end up executing the default behaviour of that input.您不是使用 AJAX 发送请求,#email_submit 是提交类型的输入,而不是按钮,因此如果您不使用preventDefault(),您最终会执行该输入的默认行为。

You have 2 options there, one is using preventDefault() and the other is to switch that input to a button, so it won't submit the form before the javascript code runs.你有两个选项,一个是使用 preventDefault() 另一个是将该输入切换到一个按钮,这样它就不会在 javascript 代码运行之前提交表单。

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

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