【问题标题】:res.render() into a div with expressres.render() 用 express 放入一个 div
【发布时间】:2017-01-20 15:17:24
【问题描述】:

我正在使用带有 express 的 nodejs,我正在尝试将 ejs 加载到这样的 div 中:

app.js(服务器端)

//SHOW
app.get("/courses/:id", function(req,res){
    console.log("requested");
    res.render('courses/show', function(err, html){
        if(err){
            console.log(err);
        }
        else{
            console.log(html);
        }
    });
});

这会在控制台中打印应该加载到 DIV 中的 HTML

main.js(客户端)

$(".course_link").on('click', function(){
  $.ajax({ 
      url: '/courses/asd',
      type: 'get',
      success: function(view) {
         $('#show_load').html(view);
      }
  });
});

我也试过了:

$(".course_link").on('click', function(){
      $('#show_load').load('/courses/asd', function(){
        alert('ayy');
      });
});

这会提醒“ayy”,但不会加载文件

HTML (ejs)

<div class="col-sm-8 courses-menu" id="show_load">

</div>

但它不会将 HTML 加载到 DIV 中,但是当我第一次单击时它会执行 console.logs 'requested',它也应该在每次单击时发出请求..

【问题讨论】:

  • 尝试附加回调处理程序以在调用 .load 函数时检查错误。你可以这样做,$('#show_load').load('/courses/asd', null, function(responseText, textStatus, xhr{alert(textStatus); // });
  • 好吧,它现在不会提醒任何东西,直到我停止服务器并且当我这样做时它只会说“错误”。所以现在它似乎在尝试加载它时卡住了?
  • 好的.. 在这种情况下,您可以尝试用alert(responseText); 代替alert(textStatus); 吗?
  • "/courses/asd" 可以适应"/courses/:id" 吗?
  • @DavidR 是的,我也提醒过这些,alert(responseText) 表示未定义,alert(xhr) 表示 [Object object] 并且 alert(textStatus) 表示“错误”

标签: javascript jquery ajax node.js express


【解决方案1】:

我觉得你需要send()html:

// if a callback is specified, the rendered HTML string has to be sent explicitly
res.render('courses/show', function(err, html) {
  res.send(html);
});

https://expressjs.com/en/4x/api.html#res.get

还要确保你的 PATH 是完整的:

var PATH = 'http://localhost:3000';    
$(".course_link").on('click', function(){
          $('#show_load').load(PATH + '/courses/asd', function(){
            alert('ayy');
          });
    });

【讨论】:

  • 是的,我已经尝试过了,虽然现在我提醒了@DavidR 告诉我的内容,它说 alert(responseText) 说要加载的 html,alert(xhr) 说 [object Object] 和alert(textStatus) 说“成功”。但它仍然不会显示任何内容
  • 路径很好,因为 app.js 确实 console.logs 输出了一些请求。我什至可以打印应该呈现的 html。此外,我发现 res.send() 只有在指定回调时才需要,必须显式发送呈现的 HTML 字符串(在您的链接中)。不过还是谢谢。
猜你喜欢
  • 2020-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-04
  • 2013-07-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多