如何使用AJAX将用户单击的元素的id传递回Flask

时间:2020-04-19 08:53:58

标签: javascript jquery ajax rest flask

我正在尝试在显示记录列表的网站上工作,当用户单击其中一个记录时,他将被导航到另一个显示记录详细信息的页面。其背后的逻辑是,每个“ li”标记都有一个唯一的“ id”属性,我可以使用该ID来调用API并获取该记录的详细信息。但是,似乎什么也没有传递回Flask ...

HTML代码:

<ul class="list-group list-group-flush">
  {%for i in range(0,length)%}
  <li class="list-group-item" id={{res.value[i].id}}>
    <h4 class="itemName">Name:{{res.value[i].name}}</h4>
    <p class="itemAssetType">{{res.value[i].assetTypes[0]}}</p>
    <p class="itemQualifiedName">{{res.value[i].qualifiedName}}</p>   
  </li>
  {%endfor%}
</ul>

JavaScript代码:

$(function(){
$('li').click(function(){
    var elementID = this.id
    var datatosend = JSON.stringify({"guid":elementID})
    $.ajax({
        url: '/details',
        data: datatosend,
        type: 'POST',
        success: function(response){
            window.location.href = '/details'
            console.log(response); //for stackoverflow: this shows None in console
        },
        error: function(ts) { alert(ts.responseText) }
    });
});

});

烧瓶代码:

@app.route('/details',methods=['POST','GET'])
def details():
    print (request.json) #this gives: None
    print (request.data) #this gives: b''
    print (request.args.get("guid")) #this gives: None
    return str(request.json)

只是想知道我应该如何将该ID传递到烧瓶中?为什么总是空的??? 我对前端有点陌生,非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

我认为您删除了这部分

success: function(response){
                window.location.href = '/details'
                console.log(response);
            }

因为您从服务器获取了一些数据,然后又转到了另一个页面?但是您的数据仍然位于上一页! 您需要保持在当前页面上,并像这样使用数据:

  success: function(response){
                        console.log(response);
                    }

$(function () {
  $('li').click(function () {
    var elementID = this.id;
    console.log(this.id)//for stackoverflow: this shows the id as I expected
    $.ajax({
      url: '/details',
      data: { guid: this.id },
      type: 'POST',
      success: function (response) {
        console.log(response);
      },
      error: function (error) {
        console.log('failed');
        console.log(error);
        console.log('element id =======>',elementID)//it is work now!!!
      }
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<li id="xyz">##click me##</li>

  <script src="app.js"></script>