我当前正在尝试从我的服务器请求数据。我使用 Flask,我的响应函数从数据库获取数据并将其转换为随后 json 化的字典列表,如下所示:
@app.route('/database/customer/<int:customer_id>/', methods=['GET'])
def customer_id(customer_id):
c, conn = connectionCust()
computerdb = c.execute("SELECT * FROM Computers WHERE customer_id=(%s)", customer_id)
computerdb = c.fetchall()
computerList = []
for computer in computerdb:
computerDict = {
'computer_id': str(computer[0]).strip('L'),
'computer_name': computer[2]}
computerList.append(computerDict)
return jsonify(computerList)
如果我输入例如http://0.0.0.0:8080/database/customer/3 它显示
[
{
"computer_id": "5",
"computer_name": "CUST3COMP1"
},
{
"computer_id": "6",
"computer_name": "CUST3COMP2"
},
{
"computer_id": "7",
"computer_name": "CUST3COMP3"
}
]
我的 ajax 代码连接到一个下拉列表,内容如下:
$('#customer').chosen().change(function(event){
if(event.target == this){
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://0.0.0.0:8080/database/customer/" + $(this).val(),
success: function(data){
alert(data);
}
});
};
});
但是我无法提醒发回的数据,当我查看日志时,它说
127.0.0.1 - - [30/Nov/2016 13:02:06] "GET /database/customer/3?callback=jQuery112006497998475787305_1480507320739&_=1480507320740 HTTP/1.1" 301 -
127.0.0.1 - - [30/Nov/2016 13:02:06] "GET /database/customer/3/?callback=jQuery112006497998475787305_1480507320739&_=1480507320740 HTTP/1.1" 200 -
我认为 jsonify() 或者 ajax 代码有问题。你们对这些事情更熟悉,也许对我如何访问我的回复有一些意见? 谢谢。
最佳答案
从 Flask 方面来看这似乎不是问题。尝试将 Ajax 调用数据类型更改为 json 而不是 jsonp 并使用 async=false :
$('#customer').chosen().change(function(event){
if(event.target == this){
$.ajax({
type: "GET",
dataType: "json",
async: false,
url: "http://0.0.0.0:8080/database/customer/" + $(this).val(),
success: function(data){
alert(data);
},
error: function(data) {
alert(JSON.stringify(data));
}
});
};
});
关于jquery - jsonify 字典列表并作为 ajax 请求的响应发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40886778/