使用Jquery $ .ajax在Flask上调用服务器端函数

时间:2017-09-27 23:02:08

标签: python ajax flask

我想使用Ajax调用服务器端函数。

我找到了一个简单的PHP in this post示例。我认为如果我们可以包含这个相同的例子,但是对于Python / Flask MVC框架,社区将会改进。

这是View端的ajax代码,名为test.html:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<script>
function create () {
$.ajax({
url:"test1", //the page containing python script
type: "post", //request type,
dataType: 'json',
data: {registration: "success", name: "xyz", email: "abc@gmail.com"},
success:function(result){
console.log(result.abc);
      }
    });
   } 
</script>

这将是Controller上的Python代码:

@app.route('/test', methods=['GET','POST'])
    def test():
        return render_template("test.html", brand = brand)

@app.route('/test1', methods=['GET','POST'])
    def test1():
        if registration == "success":
            return json.dump({"abc":'successfuly registered'});

1 个答案:

答案 0 :(得分:2)

删除视图函数的参数。使用export class QuestionPrimative { question : string = ''; id : string = ''; name : string = ''; ctrlName? : string = ''; lowExtreme? : string = ''; hiExtreme? : string = ''; template : string = ''; } export class Answer { answer : string = ''; id : string = ''; trigger? : string = ''; ctrlName? : string = ''; } export class QuestionBase extends QuestionPrimative { answers? : Answer[] = []; } export class MicroQuestions { activate : string = ''; questions : Question[]= []; } export class Question extends QuestionBase { micros? : MicroQuestions[] = []; } export class QuestionSection { name : string = ''; questions : Question[]= []; } export class QuestionnaireBody{ sections: QuestionSection[] = []; } 访问发布的数据。使用request.form返回JSON响应。视图必须从每个执行路径返回响应。

jsonify