[英]How to use Flask Jinja Template generated content and JQuery Ajax functionality?
我正在用Flask和JQuery創建一個應用程序,它接受像這樣的用戶輸入
<form> {% for i in range(length) %} <div class="form-group has-success has-feedback"> <label for="question">Question {{ i+1 }}: {{ qlist[i] }}</label> <textarea class="form-control" rows="5" id="CAT_Custom_{{ i+1 }}" name="CAT_Custom_{{ i }}"></textarea> <span class="glyphicon glyphicon-ok form-control-feedback"></span> </div> {% endfor %} <input type="submit" name="submit" class="submit action-button" value="Submit" /> </form>
這里qlist是這樣的問題列表
['What is a Network?', 'What is a Router', ...]
在提交表單之前,我要確保每個問題的答案都由用戶鍵入,至少為100個單詞。 因此,我嘗試使用一個名為process的函數,該函數根據答案的長度返回錯誤或成功。
@app.route("/process", methods=["POST"])
def process():
name = request.form['name']
if len(name.split()) >= 100:
return jsonify({'success' : name})
return jsonify({'error': 'No data'})
現在的問題是,由於我的表單輸入是動態創建的,我該如何檢查每個答案的長度是否在100個單詞以上。 我的嘗試是這樣的,但是它改變了每個textarea輸入,而不僅僅是單詞數量較少的那個。
$(function() { $('form').on('submit', function() { $.ajax({ data : { name : $(this).find('.form-control').val() }, type : 'POST', url : '/process' }) .done(function(data) { if(data.error) { $('.form-group').find('span').removeClass('glyphicon-ok').addClass('glyphicon-remove'); } else { $('.form-group').find('span').removeClass('glyphicon-remove').addClass('glyphicon-ok'); } }); event.preventDefault(); }); });
我找到了解決我這樣的問題的方法
$(function() { $('.form-group').focusout( function(event) { var target = $(this); $('.form-group').each(function() { var target = $(this); $.ajax({ data : { name : target.find('.form-control').val() }, type : 'POST', url : '/process' }) // Ajax close .done(function(data) { if(data.error) { target.find('span').removeClass('glyphicon-ok').addClass('glyphicon-remove'); } else { target.find('span').removeClass('glyphicon-remove').addClass('glyphicon-ok'); } // if close }); // done close event.preventDefault(); }); // each close }); });
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.