【问题标题】:How to submit a Flask-WTF form with Ajax如何使用 Ajax 提交 Flask-WTF 表单
【发布时间】:2015-12-24 23:47:40
【问题描述】:

我希望能够采用此表单 - 获取带有条带结帐的条带 ID(代码已实现且正常工作),然后通过 ajax 提交表单并将条带 ID 插入表单中的隐藏值中。

什么 jQuery 代码可以让我这样做?

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 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>

【问题讨论】:

  • amount = 2500; 请告诉我您不相信客户会告诉您收取多少费用!
  • 不 - 金额由定义注册类型的 url 参数定义 - 由后端逻辑定义的金额。这只是向用户显示他们将被收取多少费用(假设他们不是故意破坏东西) - 无论哪种方式,他们仍将根据注册类型收取费用。
  • 唷 ;) 这真是一种解脱!

标签: jquery python ajax flask flask-wtforms


【解决方案1】:

我可能会使用 jQuery 的 serialize 方法尝试类似的操作。

<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 中。

您也可以选择将 ajax 调用保留为 'POST',如果您想推出自己的解决方案,您需要查看 jQuery 的 serializeArray,或者查看我改编的以下代码this stackoverflow question:

// 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 来读取您的 &lt;form&gt; 数据并对其进行参数化。如果可能的话,您希望避免对您的帖子data 进行硬编码。这样做很麻烦,而且以后要更改它更麻烦。

【讨论】:

    【解决方案2】:

    最后我这样做了,我希望有一个更简单的方法:

    <script>
            $(document).ready(function(){    
                $('#submit').click(function() {
                    console.log('submit clicked')
    
                    data = {
                        'csrf_token': '{{ csrf_token() }}',
                        'csrftoken': '{{ csrf_token() }}',
                        'stripetoken': gtoken,
                        'forename': $('#forename').val(),
                        'surname': $('#surname').val(),
                        'username': $('#username').val(),
                        'password1': $('#password1').val(),
                        'password2': $('#password2').val(),
                        'email':  $('#email').val(),
                        'phone': $('#phone').val(),
                        'addressLine1': $('#addressLine1').val(),
                        'addressLine2': $('#addressLine2').val(),
                        'town': $('#town').val(),
                        'county': $('#county').val(),
                        'postcode': $('#postcode').val(),
                        'recurringDonationQuantity':  $('#recurringDonationQuantity').val(),
                    }
    
                    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({
                        url: '',
                        data: JSON.stringify(data, null, '\t'),
                        type: 'POST',
                        contentType:'application/json;charset=UTF-8',
                        success: function(response) {
                            console.log(response);
                        },
                        error: function(error) {
                            console.log(error);
                        }
                    });
                });
            });
        </script>
    

    有这么多 csrf 的东西,因为我还没有弄清楚是哪一个使它起作用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-11-22
      • 2014-09-13
      • 1970-01-01
      • 1970-01-01
      • 2021-10-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多