查询数据库时,从通过getJSON获得的列表中删除一个项

2024-04-29 13:55:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个在查询数据库时获得的项目列表。查询结果用jsonify处理,最后通过getJson获得,方法如下:

$(function() {
    $.getJSON($SCRIPT_ROOT + '/appointments/', function(data) {
        var output="<ul>";
        for (var i in data.appts) {
            output+="<li>" + data.appts[i].labo + "</li>"
        }
        output+="</ul>";
        $("#result").html(output)                  
    return false;
  });
});

到目前为止还不错。。。你知道吗

现在我需要通过调用(例如)下面的Flask函数来提供删除上面列出的每个项的可能性:

@app.route('/appointments/<int:appointment_id>/delete/', methods=['DELETE'])
def appointment_delete(appointment_id):
    appt = db.session.query(Appointment).get(appointment_id)
    db.session.delete(appt)
    db.session.commit()
    return jsonify({'status': 'OK'})

不幸的是,我不知道如何将这两段代码连接起来。既然我已经为此挣扎了一段时间,我会感激任何能让我走出泥潭的帮助。。。谢谢。!你知道吗

根据@dcodesmith的评论编辑

getJSON反应:

{
   "appts":[
      {
         "id":1,
         "day":"Mardi",
         "labo":"l1",
         "modified":[
            "21/01/2014"
         ],
         "groups":"5",
         "plage_h":"10h00",
         "sem":"5",
         "start":[
            "28/01/2014"
         ]
      },
      {
         "id":4,
         "day":"Vendredi",
         "labo":"l1",
         "modified":[
            "22/01/2014"
         ],
         "groups":"5",
         "plage_h":"10h00",
         "sem":"5",
         "start":[
            "31/01/2014"
         ]
      }
   ]
}

Tags: idoutputdbdatasessionvarfunctiondelete
1条回答
网友
1楼 · 发布于 2024-04-29 13:55:49

需要更改

  • 首先,编辑输出HTML以包含一个锚定标记,该锚定标记应该有一个dataid属性,并为其分配appts id。你知道吗
  • 在appt列表中的锚定标记上创建一个click事件

代码

$(function() {

    $.getJSON($SCRIPT_ROOT + '/appointments/', function(data) {
        var output = "<ul>";
        for (var i in data.appts) {
            var appt = data.appts[i];
            output += "<li>" + appt.labo + "<a href='#' class='delete' data-id=" + appt.id + ">delete</a></li>"
        }
        output+="</ul>";
        $("#result").html(output)                  
        return false;
    });


    $(document).on('click', 'a.delete', deleteAppt);

    function deleteAppt(e){
        e.preventDefault();
        var $this = $(this),
            id = $this.data('id'),
            url = "/appointments/" + id + "/delete/";
        $.ajax({
            url: url,
            type: 'POST',
            data: {id: id}
        })
        .done(function(data, textStatus, jqXHR){
            if (data.status === 'OK'){
            // if successful remove deleted row
                $this.parent('li').remove();
            }
        })
        .fail(function(jqXHR, textStatus, errorThrown){
            //log your error here, if any is caught. This will be very helpful for debugging
        })
    }
});

注意:我对烧瓶一窍不通,但这应该能起作用

相关问题 更多 >