JavaScrip ajaxt和python flask通過json傳遞資料的方法
阿新 • • 發佈:2019-01-01
JavaScript呼叫ajax傳送一個json
$('#cc').click(function () { mdffilepath = { 'name1': 'aaaa1','name2': 'aaaa2','name3': 'aaaa3','name4': 'aaaa4'//要傳送的字典,在JavaScript裡被定義為物件 }; //傳輸資料 $.ajax({ type: 'POST', url: '/calc/read_inca_func', data: JSON.stringify(mdffilepath),//將物件打包成json的字串傳送,對應下面也要將字串解碼成字典 contentType: 'application/json;charset=UTF-8',//編碼格式 dataType: 'json', success: function (data) { console.log(typeof(data["calc"]));//列印為字串 console.log(data["calc"]);//列印為物件object } }) })
from flask import Flask,render_template, request, url_for, jsonify import os import json import sys import subprocess app = Flask(__name__)//與下面的 app.run()對應 app.config['SECRET_KEY'] = "dfdfdffdad"//抄的,不知道幹嘛 @app.route('/') def index(): return render_template('index.html') @app.route('/calc/read_inca_func', methods=['POST']) def upload_file(): a=request.get_data()//得到JavaScript傳送的字串流 print(type(a))//bytes s1 = str(a, encoding='utf-8')//解碼為string print(type(s1)) print(s1) user_dict1 = json.loads(s1)//將string變成dict for key in user_dict1.keys(): print(key,user_dict1[key]) user_dict = json.loads(a)//將bytes變成dict # info = eval(str(requests.post(url_now).content.decode()))//抄的,不知道什麼意思 for key in user_dict.keys(): print(key,user_dict[key]) dict4={"calc":"fail"} return jsonify(dict4) if __name__ == '__main__'://flask例項化,上面相當於類的子函式 app.run()