2016-09-05 5 views
-1

私が作成しているプレゼンテーション用のインタラクティブなWebサイトを設計しようとしています。私はこのフラスコのもので新しく、私のコードがうまくいかない理由を理解するのに苦労しています。jQueryとFlaskを使用してjsからpython関数を呼び出そうとしています

私はウェブサイトを作成しようとしています。その中のすべての行はクリック可能です。クリックすると、行のテキストに従って計算を行い、そのテキストを置き換えるPython関数をバインドします。私も、私は私のWebページ上のいくつかの行をクリックするとバインドされるべきフラスコのコードを書いた

<!doctype html> 
<html lang="en"> 
<head> 
    <meta charset="utf-8"> 
    <title>click demo</title> 
</head> 
<body> 


<p>2016-04-21 09:12:59</p> 
<p>Second Paragraph</p> 
<p>2016-04-21 09:12:59 bla bla</p> 

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
<script> 

$("p").click(function() { 
    $.getJSON('/background_process', { 
     line: $(this).text(), 
    }, function(data) { 
     $(this).text(data.result); 
    }); 
     return false; 
}); 

</script> 

</body> 
</html> 

from flask import Flask, jsonify 
app = Flask(__name__) 
from flask import render_template 
import re 


@app.route("/") 
def index(): 
    return render_template('index.html') 

@app.route("/background_process") 
def background_process(): 
    try: 
     lang = request.args.get('line', 0, type=str) 
     string = lang.split()[0] 
     if re.match(r'\d\d\d\d-\d\d-\d\d',string): 
      return jsonify(result=string) 
     else: 
      return jsonify(result="Doesnt start with a date") 
    except Exception as e: 
     return str(e) 
if __name__ == "__main__": 
    app.run() 

問題は機能がないことである私は、単純なHTMLを構築する必要がありそのために htmlページにスロットのIDでテキストを置く場所を指定していない限り、何らかの理由で動作しません。何が問題になったのか理解できません。

答えて

1

あなたのアプリには2つの問題があります。 最初のものは、あなたが要求モジュールをインポートしていないことである。

from flask import Flask, jsonify, request 

第二には、テンプレートでは、あなたが範囲外であるthisを参照しています。 これは動作するはずです:

$("p").click(function() {                    
    var this_p = this;                      
    $.getJSON('/background_process', {                  
     line: $(this_p).text(),                   
    }, function(data) {                     
     $(this_p).text(data.result);                  
    });                         
     return false;                      
}); 
関連する問題