簡體   English   中英

添加參數時,為什么我的ajax獲取請求找不到我的處理程序路由?

[英]Why can't my ajax get request find my handler route when I add arguments?

我正在構建一個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不執行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結合使用的解決方案對我來說效果很好。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM