node.js - 在视图中调用时如何从 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>
解决方案
“像 <% %> 这样的 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 是什么样的。如果您使用更多代码更新您的问题,我可以进一步为您提供帮助。
推荐阅读
- angular - Angular 5 应用架构设计
- c++ - 使用 std::ifstream 和 getc 读取换行符的区别
- ionic-framework - 我对命令 Ionic 3 和 Firebase 和 angularfire2 有问题
- batch-file - windows bat文件:回显字符串而不执行它
- python-2.7 - 在另一列pyspark中创建具有字符串长度的列
- c# - 如何将相机添加到 Matrix4x4 旋转
- heroku - 在打开 heroku 的情况下获取多个应用程序的列表
- python - 从 100.21 Hz 到 8 Hz 下采样信号(非整数抽取因子)
- sublimetext3 - Sublime Text 3:主配置?(用于:灾难恢复、移植到新机器等)
- javascript - 比较 2 个数组并分配匹配值