flask和ajax通信详细步骤与完整代码
生活随笔
收集整理的這篇文章主要介紹了
flask和ajax通信详细步骤与完整代码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
##################################下面是思路############################################
flask的api至少寫兩個函數:
一個用來返回頁面;
一個用來響應頁面上ajax的get請求
##################################下面是實驗步驟############################################
1.
nginx -c?/etc/nginx/nginx.conf
nginx -s reload
python hello.py
2.打開http://127.0.0.1:10072/index
3.點擊""
得到:
##########################################下面是附錄#########################################
結構是:
├── hello.py
├── templates
│???└── get_example.html
└── 實驗說明.txt
hello.py
from flask import Flask,render_template app = Flask(__name__)@app.route('/index',methods=['GET', 'POST']) def index():return render_template("get_example.html")@app.route('/ajax_get',methods=['GET', 'POST']) def ajax_data():return "這個是來自flask的數據"if __name__ == '__main__':app.run("127.0.0.1",port=10071,debug=True)get_example.html
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>菜鳥教程(runoob.com)</title> <script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"> </script> <script> $(document).ready(function(){$("button").click(function(){$.get("ajax_get",function(data,status){alert("數據: " + data + "\n狀態: " + status);});}); }); </script> </head> <body><button>發送一個 HTTP GET 請求并獲取返回結果</button></body> </html>/etc/nginx/nginx.conf
user root; worker_processes 2; error_log /usr/local/nginx/error.log; pid /usr/local/nginx/nginx.pid;events {worker_connections 1024; }http {include /usr/local/nginx/conf/mime.types;default_type application/octet-stream;server {listen 10072;server_name localhost;access_log /var/log/nginx/access.log;#配置跨域#add_header Access-Control-Allow-Origin *;#add_header Access-Control-Allow-Headers X-Requested-With;#add_header Access-Control-Allow-Methods GET,POST,OPTIONS;location / {#root /home/appleyuchi;#autoindex on;proxy_pass http://127.0.0.1:10071;proxy_set_header Host $host;proxy_set_header X-Real-IP $remote_addr;proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;}}}?
總結
以上是生活随笔為你收集整理的flask和ajax通信详细步骤与完整代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 通俗理解回调函数
- 下一篇: ajax请求flask以后得到的响应查看