如何使用Ajax提交Flask-WTF表单 [英] How to submit a Flask-WTF form with Ajax

查看:220
本文介绍了如何使用Ajax提交Flask-WTF表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够采用这种形式-获取带有条带签出的条带ID(代码已实现且正在运行),然后通过ajax提交表单并将条带ID插入表单中的隐藏值中.

I want to be able to take this form - get a stripe ID with stripe checkout (code implemented and working) and then submit the form via ajax and insert the stripe id into the hidden value in the form.

什么jQuery代码可以让我做到这一点?

What jQuery code would allow me to do this?

class signupForm(Form):
forename = StringField('Forename', validators = [ Required()])
surname = StringField('Surname', validators = [Required()])
username = StringField('Username', validators = [Required(), Length(min = 4, max = 20)])
password1 = PasswordField('Password', validators = [Required(), Length(min = 6, max=50)])
password2 = PasswordField('Password', validators = [Required(), Length(min = 6, max=50)])
email = StringField('Email', validators = [Email(), Required()])
phone = StringField('Phone number', validators = [Required()])
addressLine1 = StringField('Address Line 1', validators = [Required()])
addressLine2 = StringField('Address Line 2')
town = StringField('Town', validators = [Required()])
county = StringField('County', validators = [Required()])
postcode = StringField('Postcode', validators = [Required()])
recurringDonationQuantity = StringField('If you would like to make a monthly recurring donation, please enter the amount in Sterling below. <br> Recurring Donation Amount')
stripetoken = HiddenField('')

我的页面:

            {% with messages = get_flashed_messages() %}
                {% if messages %}
                    <div class="alert alert-warning" role="alert">
                        <ul>
                                {% for message in messages %}
                                    <li>{{ message | safe }}</li>
                                {% endfor %}
                        </ul>
                    </div>
                {% endif %}
            {% endwith %}

            {{ wtf.quick_form(form) }}

我也有此javascrpt页内

I also have this javascrpt in-page

            <script>
            var handler = StripeCheckout.configure({
                key: '{{key}}',
                image: '{{ url_for("static", filename="logo.png") }}',
                locale: 'english',
                token: function(token,args) {
                    $('#stripe-token').val = token;
                    wt
                    console.log(token)
                }
            });


            $('#pay').on('click', function(e) {
                // Open Checkout with further options

                    if ('{{type}}' == 'normal') {
                        description = 'Normal Membership';
                        amount = 2500;

                        console.log('membership type is NORMAL')
                    } else {
                        description = 'Associate Membership';
                        amount = 2500;

                        console.log('membership type is ASSOCIATE')
                    }



                    handler.open({
                        name: 'My Organisation',
                        description: description,
                        amount: amount,
                        currency: 'GBP',
                        panelLabel: 'Okay',
                        billingAddress: true,
                        zipCode: true
                    });

                    e.preventDefault();
            });


            // Close Checkout on page navigation
            $(window).on('popstate', function() {
            handler.close();
            });
        </script>

推荐答案

我可能会使用jQuery的 serialize 方法.

I might try something like this using jQuery's serialize method.

<script>
    $(document).ready(function(){    
        $('#submit').click(function() {
            console.log('submit clicked');

            //This part keeps you D.R.Y.
            url_params = $(this).serialize();

            //left this code the same...
            var csrftoken = $('meta[name=csrf-token]').attr('content')

            $.ajaxSetup({
                beforeSend: function(xhr, settings) {
                    if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                        xhr.setRequestHeader("X-CSRFToken", csrftoken)
                    }
                }
            })

            $.ajax({
                //more changes here
                url: url_params, //you may need to modify this to hit the
                                 //correct URL depending on your forms action param
                                 //ex: url: $(this).attr('action') + url_params,
                type: 'GET',     //GET instead of POST so we can use url_params
                contentType:'application/json;charset=UTF-8',
                success: function(response) {
                    console.log(response);
                },
                error: function(error) {
                    console.log(error);
                }
            });
        });
    });
</script>

希望这可以为您指明正确的方向,从而避免将太多字段硬编码到您的javascript中.

Hopefully this points you in the right direction to avoid having to have so many fields hard-coded into your javascript.

您还可以选择将ajax调用保留为'POST',为此,您需要查看jQuery的此stackoverflow问题:

You may also choose to keep the ajax call as a 'POST', to do that you would need to take a look at jQuery's serializeArray if you want to roll your own solution, or see the following code I adapted from this stackoverflow quesion:

// add a helper function to the $ jQuery object.
// this can be included in your page or hosted in a separate JS file.
$.fn.serializeObject = function()
{
    var o = {};
    var a = this.serializeArray();
    $.each(a, function() {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

// then inside your form page:
<script>
    $(document).ready(function(){    
        $('#submit').click(function() {
            console.log('submit clicked');

            //This part keeps you D.R.Y.
            data = $(this).serializeObject();

            //left this code the same...
            var csrftoken = $('meta[name=csrf-token]').attr('content')

            $.ajaxSetup({
                beforeSend: function(xhr, settings) {
                    if (!/^(GET|HEAD|OPTIONS|TRACE)$/i.test(settings.type) && !this.crossDomain) {
                        xhr.setRequestHeader("X-CSRFToken", csrftoken)
                    }
                }
            })

            $.ajax({
                //more changes here
                data: data,
                url: '',
                contentType:'application/json;charset=UTF-8',
                success: function(response) {
                    console.log(response);
                },
                error: function(error) {
                    console.log(error);
                }
            });
        });
    });
</script>

这里要摘录的关键是,您可以使用javascript或jQuery读取<form>数据并将其参数化.您要尽可能避免对帖子data进行硬编码.这是一件麻烦事,而将其更改为一条线则是一个更大的麻烦事.

The key to take away here is that you can use javascript or jQuery to read your <form> data and parameterize it. You want to avoid hard-coding your post data if at all possible. It's a hassle to do, and it's a bigger hassle to change it down the line.

这篇关于如何使用Ajax提交Flask-WTF表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆