因此,我在Flask上运行了这个简单的python脚本,我希望通过ajax jQuery请求将变量传递给它。我可能漏掉了一些显而易见的东西,但我不能让它正常工作。
@app.route('/test', methods=['GET', 'POST'])
def test():
my_int1 = request.args.get('a')
my_int2 = request.args.get('b')
my_list = [my_int1, my_int2]
with open('my_csv.csv', 'wb') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(my_list)
return '' #does one have to have an return even tho it is just a script?因此,当将参数传递给URL字段:http://127.0.0.1:5000/test?a=10&b=25时,上面的操作将很好,但是,在铬控制台中尝试此操作将根本不会产生任何输出:
$.ajax({
method: "POST",
url: "127.0.0.1:5000/test",
data: {a: 10, b: 25},
dataType: "script"
});我缺少什么,为什么上面的jquery请求不能工作?$.ajax is not a function(…)
发布于 2016-09-02 20:51:16
请尝试使用下面的代码,如果这是您想要的,请告诉我:
from flask import Flask, request
import csv
app = Flask(__name__)
@app.route('/test', methods=['GET', 'POST'])
def test():
if request.is_xhr:
a = request.json['a']
b = request.json['b']
else:
a = request.args.get('a')
b = request.args.get('b')
my_list = [a, b]
with open('my_csv.csv', 'wb') as myfile:
wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
wr.writerow(my_list)
return '''
<html>
<head>
<title>This is just a testing template!</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</body>
</html>
'''
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=True)要从Chrome控制台进行测试,首先需要转到http://127.0.0.1:5000/test (在此之后,jQuery将在浏览器中可用),然后运行以下代码:
$.ajax({
url: "http://127.0.0.1:5000/test",
method: "POST",
headers: {'Content-Type':'application/json'},
data: JSON.stringify({a: 10, b: 25}),
success: function(data){console.log('result: ' + data);}
});如果存在跨源问题,请将以下代码添加到app.py文件中:
@app.after_request
def after_request(response):
response.headers.add('Access-Control-Allow-Origin', '*')
response.headers.add('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept')
response.headers.add('Access-Control-Allow-Methods', 'GET, PUT, POST, DELETE, OPTIONS')
return response发布于 2016-09-02 18:04:12
请参阅http://flask.pocoo.org/docs/0.11/api/#flask.Request
request.args : If you want the parameters in the URL
request.form : If you want the information in the body (as sent by a html POST form)
request.values : If you want both尝尝这个
@app.route('/test', methods=['GET', 'POST'])
def test():
my_int1 = request.values.get('a')
my_int2 = request.values.get('b')发布于 2016-09-02 18:40:04
您的jQuery引用似乎没有加载或不正确,请将其添加到HTML页面的<head> here </head>部分。
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>https://stackoverflow.com/questions/39298249
复制相似问题