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()
来源:51CTO
作者:山药当人参
链接:https://blog.51cto.com/14156081/2337490