Ajax和flask的问题是什么?

时间:2019-08-05 02:43:23

标签: python jquery flask

我想与ajax后端共享视图,我正在尝试但未在控制台中显示后端“ HELLO”的消息,这是什么问题?

       <script type=text/javascript>
        $(function() {
          $('a#test').bind('click', function() {
            $.getJSON('/background_process_test',
                function(data) {
              //do nothing
            });
            return false;
          });
        });
</script>
//button
<div class='container'>
    <h3>Test</h3>
        <form>
            <a href=# id=test><button class='btn btn-default'>Test</button></a>
        </form>

</div>

我的后端是这个,我正在使用框架烧瓶

from flask import Flask, jsonify
from flask_cors import CORS, cross_origin

app = Flask(__name__)
CORS(app, support_credentials=True)


@app.route('/background_process_test')
@cross_origin(supports_credentials=True)
def background_process_test():
    print "Hello"
    return "nothing"   



if __name__ == "__main__":
  app.run(host='0.0.0.0', port=8000, debug=True)


@app.route("/login")
@cross_origin(supports_credentials=True)
def login():
  return jsonify({'success': 'ok'})

此错误我得到:

Access to XMLHttpRequest at 'file:///background_process_test' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

1 个答案:

答案 0 :(得分:1)

毕竟有两个问题:

  • 不是从flask / server中提供HTML。而且出于安全原因,浏览器可能会阻止它。我将HTML直接放在函数index()中,但稍后您可以使用render_template("filename.html")

  • 您忘记加载JavaScript jQuery库。

在链接中的代码中,两个元素都存在-因此,您应该已经可以使用代码:Flask - Calling python function on button OnClick event

from flask import Flask, jsonify
from flask_cors import CORS, cross_origin


app = Flask(__name__)
CORS(app, support_credentials=True)


@app.route('/')
def index():
    return """
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<script type=text/javascript>
   $(function() {
     $('a#sender').bind('click', function() {
       $.getJSON('/background_process_test',
         function(data) {
           console.log(data);
           window.alert(data['success'])  
         });
       return false; // stop <a> to send normal request
     });
   });
</script>

<form>
    <a href=# id="sender"><button>Send AJAX</button></a>
</form>

</div>"""

@app.route('/background_process_test')
@cross_origin(supports_credentials=True)
def background_process_test():
    print("Hello AJAX")
    return jsonify({'success': 'OK'})


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8000)