我正在构建一个Web应用程序,该应用程序显示有关存储在本地服务器运行瓶中的花朵的数据。
我的前端是html,带ajax的js;
我的后端是带瓶的蟒蛇
在浏览器中,有一个空的div,其中将显示数据。
在它的下面有一排图像。当用户单击图像时,数据应显示在上方的div中。
我尝试使用$ .ajax而不是$ .get,并且得到相同的结果。
这是我在js中的事件监听器:
$('.image').click((e)=>{
$('.selected').removeClass('selected');
$(e.target).addClass('selected'); // just a visual indication
$.get('/flowerdesc/'+$(e.target).attr('id')).done((data)=>{
flowerInfo = JSON.parse(data);
$('#flower-title').empty();
$('#flower-title').html(flowerInfo.name);
$('.desc-text').empty();
$('.desc-text').html(flowerInfo.description);
})
})
这是我的请求处理程序:
@get('/flowerdesc/<flower>')
def get_flower_desc(flower):
return json.dumps(data[data.index(filter(lambda f: f.name == flower, data)[0])])
(数据是一个字典数组,每个字典都包含一朵花的数据)
我收到了可能由于参数而发生的404错误(根本未执行功能
get_flower_desc
),因为每当我使用不带参数且不传入参数的aa函数时,我得到的结果就是期待。 最佳答案
我发现我必须精确地制定一个AJAX请求,以使其在类似的情况下与Bottle一起很好地工作。
这是一个带有GET请求的示例。您可以将此函数附加到事件处理程序,也可以将其直接移动到事件处理程序。
function getFlowerData(id) {
$.ajax({
type: "GET",
cache: false,
url: "/flowerdesc/" + id,
dataType: "json", // This is the expected return type of the data from Bottle
success: function(data, status, xhr) {
$('#flower-title').html(data['name']);
$('.desc-text').html(data['description']);
},
error: function(xhr, status, error) {
alert(error);
}
});
};
但是,我发现使用AJAX的POST请求获得了更好的结果。
function getFlowerData(id) {
$.ajax({
type: "POST",
cache: false,
url: "/flowerdesc",
data: JSON.stringify({
"id": id,
}),
contentType: "application/json",
dataType: "json",
success: function(data, status, xhr){
$('#flower-title').html(data['name']);
$('.desc-text').html(data['description']);
},
error: function(xhr, status, error) {
alert(error);
}
});
};
对于POST请求,Bottle中的后端应如下所示。
@post("/flowerdesc") # Note URL component not needed as it is a POST request
def getFlowerData():
id = request.json["id"]
# You database code using id variable
return your_data # JSON
确保您的数据是有效的JSON,并且您拥有的数据库代码正常运行。
这些结合使用AJAX和Bottle的解决方案对我来说效果很好。