我正在编写以下HTML代码
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="/static/css/grafana_style_sheet.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
$("#Click").click(function(){
alert('hi '+ $('#databases').val());
var data1 = new Object();
data1.name = $('#databases').val();
data1.dbname = 'grafana';
alert(data1.dbname + " " + data1.name);
$.ajax({
url : "dashboards",
type : 'POST',
data : 'data1',
dataType : "text",
success : function(){
data = JSON.parse(data);
console.log("hi " + data);
}
});
});
});
</script>
</head>
<body>
<div id="header">Report Suites</div>
<form>
<fieldset id = "fieldset">
<legend align = "center"><font color= "#00008B"><strong>Select your Report Suite<strong></font></legend>
<select id ="databases" name = "db">
<option value = "">--Select From following--</option>
<option value = "HARMONY">HARMONY</opton>
<option value = "CAMPS">CAMPS</opton>
<option value = "QBSU">QBSU</opton>
<option value = "SIMBA">SIMBA</opton>
</select>
<br><br>
<button type = "button" id = "Click"> Click Me!!</button>
</fieldset>
</form>
<div id ="placeholder"></div>
</body>
</html>
为了运行上面的HTML代码,我使用Flask编写了以下Python程序,以便从表单(上面)发送数据并基于它运行查询。
from flask import Flask, render_template, json, request
from flask import Flask, request, abort, jsonify
from flaskext.mysql import MySQL
import MySQLdb
app = Flask(__name__)
def connection(database):
db = MySQLdb.connect("localhost","root","",database)
cursor = db.cursor()
return cursor
@app.route("/")
def main():
return render_template('grafana_try1.html')
@app.route("/dashboards",methods=['POST'])
def connect():
dtb = request.form['dbname']
b = request.form['name']
conn = connection(dtb)
conn.execute("SELECT * FROM SuiteDetails WHERE RS_name=%s",b)
results = conn.fetchall()
json_return_value =[]
for result in results:
table_data = {'RS_name' : result[0], 'RS_id' : result[1], 'Staging_db' : result[2], 'Trans_db' : result[3], 'Base_Date' : result[4], 'graph_link' : result[5]}
json_return_value.append(table_data)
print json.dumps(json_return_value)
return json.dumps(json_return_value)
if __name__ == "__main__":
app.run(debug = True)
当我在firefox上运行它时,我得到400 BAD REQUEST响应。
请告诉我我做错了什么。
答案 0 :(得分:1)
我认为问题出在jQuery POST中,你没有传递完整的url,只是动作而你想传递unsorted
而不是data1
(你想要的是对象,而不是字符串)。所以而不是:
'data1'
你应该:
$.ajax({
url : "dashboards",
type : 'POST',
data : 'data1',
dataType : "text",
success : function(){
data = JSON.parse(data);
console.log("hi " + data);
}
});
请注意,您应该更改主机$.ajax({
url : "http://<YOUR_HOST>/dashboards",
type : 'POST',
data : data1,
dataType : "text",
success : function(){
data = JSON.parse(data);
console.log("hi " + data);
}
});
,如果您在本地运行它(并且使用烧瓶默认值),它应该是<YOUR_HOST>
。
希望这有帮助