【问题标题】:Is there a way to replace an HTML variable with a Javascript variable?有没有办法用 Javascript 变量替换 HTML 变量?
【发布时间】:2021-01-14 23:27:55
【问题描述】:

所以我在 html 中有一个名为“posts”的变量,并在 for 循环中使用它来创建一系列很好的帖子。

   {% for post in posts %}
     {% with  voteform = voteform, votes = votes, post = post %}
       {%include "postlayout.html"%}

     {% endwith %}
   {% endfor %}
 </div>

然后我使用 Ajax 从烧瓶中检索一个新的查询列表,并根据用户选择的过滤器返回另一系列帖子。

    $('input[type=checkbox]:checked').each(function(){
      all.push($(this).val());
    });
    console.log(all)
    var moods = {
      'filters': all
    };
    $.ajax({
      url : "/update",
      type: 'POST',
      data: JSON.stringify(moods),
      contentType: 'application/json;charset=UTF-8',
      success: function(resp){
        $('div#response').html('posts <br>')

        for (var key in resp.data) {
          var val = resp.data[key]
          console.log(val)
          $('div#response').append(resp.data[key]['songname'] + ' by ' +
           resp.data[key]['artist'] + '<br>')
      }

        console.log(resp.data)
      },
      error: function(error){
        console.log(error)
      }
     });
    }

所以我想知道是否有办法将我的 html 代码中的“posts”替换为我的 json 代码中的“resp.data”。

【问题讨论】:

  • HTML 中没有变量

标签: javascript html ajax flask


【解决方案1】:

很遗憾,没有。

Flask 模板在发出 AJAX 请求之前被渲染到 HTML 服务器端,因此您不能在 Flask 模板中使用 AJAX 响应。

您必须使用 JavaScript(或/和 jQuery)循环响应数据并插入所需的 HTML。

【讨论】:

  • 当吉特。问题是当我这样做时,Ajax 似乎把所有东西都变成了一个 href,链接到 #.
  • jQuery 是 javascript.
猜你喜欢
  • 2019-07-19
  • 2021-09-29
  • 2018-02-19
  • 1970-01-01
  • 2017-10-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多