2015-09-27 28 views
1

我希望能夠採用這種形式 - 獲取帶有條紋簽出(代碼實現和工作)的條帶ID,然後通過ajax提交表單並將條形ID插入到隱藏在窗體中的值。如何使用Ajax提交Flask-WTF表單

什麼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的頁

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

'amount = 2500;'請告訴我你不信任客戶告訴你要收多少錢! – Monkpit

+0

Nope - 金額由一個url參數定義,它定義了註冊類型 - 由後端邏輯定義的金額。這只是向用戶顯示他們將收取多少費用(假設他們不是故意破壞的) - 無論哪種方式,他們仍然按照註冊類型收費。 – user3818253

+0

Phew;)這是一種解脫! – Monkpit

回答

0

最後,我這樣做,我希望有一個更簡單的方法:

<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的東西,因爲我還沒有到處搞清楚哪一個工作起來了。

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',要做到這一點,你需要,如果你想推出自己的解決方案,或請參閱下面的代碼我改編自this stackoverflow quesion來看看jQuery的serializeArray

// 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。這是一件很麻煩的事情,把它換下來是一件更麻煩的事情。