首页 > 解决方案 > 在视图中调用时如何从 ajax 结果集在 ejs 视图中显示数据

问题描述

我有一个空ejs视图,但我想显示我在ejs视图中调用的 ajax 调用的结果集

<script>
 // Fetch 
  $.ajax(`/x`).done(function(data, textStatus, xhr){
console.log(data);
console.log(textStatus);
console.log(xhr);      
  });

</script>
<!-- how do I loop the data received from above and display the content here? -->

我不知道该怎么做。

更新

这就是我现在所拥有的。有没有更简洁的方法来做到这一点而不是附加为 html?

<script>
  const gId = '<%= gId %>';

  // Fetch the current users c here from `/g/${gId }/c `
  $.ajax(`/g/${gId }/c `).done(function(data, textStatus, xhr){
    var c = '';
    $.each(data, function(index, value){
      console.log(index);
      console.log(value)
      c += '<div class="col-sm-6 col-md-2"><div><img class="col-sm-12 col-md-11" src="'+value.image+'" /></div><div class="text-center"><input name="card" id="card" type="checkbox" value="'+value.value+'" /> Discard</div></div>';
    });

    $('#c ').append('<div class="row"><div class="row col-sm-12">'+c +'</div><div class="col-xs-2"></div></div>');

    $('#c ').append('<button type="submit">c </button>');
  });

  const checkExchangeStatus = function(){
    $.ajax(`/g/${gId}/allExchanged`).done(function(data, textStatus, xhr){
      if (xhr.status !== 202) { // not pending
        document.location = `/g/${gId}/result`;
      }
    })
  }

  setInterval(checkExchangeStatus, 1000);
</script>
<form method="POST" action="/g/<%= gId %>/exchange">
<div id="c ">
</div>
<div>
<br/>gId : <%= gId %>
</div>
</form>

标签: node.jsejs

解决方案


“像 <% %> 这样的 ejs 代码在服务器上执行并呈现为 html。所以你不能将 ejs 代码与 ajax 请求一起使用。”

您可以做的是进行 ajax 调用,然后使用 jQuery 更改您的 html 页面。

我有一个空的 ejs 视图,但我想显示我在 ejs 视图中调用的 ajax 调用的结果集。

<script>
  $.ajax(`/x`).done(function(data, textStatus, xhr){
    console.log(data); //I am assuming this prints
      $('#someID').html(data);
  });
</script>

我不知道您期望什么结果,或者您的 html 是什么样的。如果您使用更多代码更新您的问题,我可以进一步为您提供帮助。


推荐阅读