如何从服务器返回一个HTML模式目标视图?

我想在网站上有一个button,用bootstrap打开一个模式视图。 像这样:

<button class="btn btn-primary btn-lg" id="modalButton" data-toggle="modal" data-target="#myModal"> Launch demo modal </button> 

所以这个button是针对一个叫#myModal的视图。 我不想从客户端html加载#myModal视图, 而是想向服务器发出一个AJAX请求来获取#myModal视图,因为视图将根据用户是否是admin而不同,并且该variables驻留在服务器上。

所以请求会是这样的:

 $('#modalButton').click() -> var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET","/modalFeedback",true); xmlhttp.send(); 

然后,/ modalfeedback路由应该检查用户是否是admin,并发回相应的#myModal视图。 我很困惑如何实现这一点, 更具体地说,如何从服务器返回#myModal视图,以便它正常打开。

如果有人能帮我一些伪代码,这将是非常有益的!

UPDATE

我得到它与引导远程选项工作(见下面的答案),这里是我如何调用模态:

 a#uservoice_tab(data-toggle="modal", href="/modalFeedback.html", data-target="#myModal") img(src='/img/icon-idea.png') // You need to have #myModal element in the same place you have the button. Bootstrap injects the body into this element remotely #myModal.modal.fade(tabindex='-1', role='dialog', aria-labelledby='myModalLabel', aria-hidden='true') 

这是jade中的modalFeedback.html源代码

 .modal-dialog .modal-content .modal-header button.close(type='button', data-dismiss='modal', aria-hidden='true') × h4#myModalLabel.modal-title Modal title .modal-body .modal-footer button.btn.btn-default(type='button', data-dismiss='modal') Close button.btn.btn-primary(type='button') Save changes 

由于你似乎使用引导程序,它实际上有内置的,所以你不必自己做ajax调用。 看看模式的remote选项。

您返回的内容只需要是您希望在模式内容中使用的HTML片段。

如果你使用express,你将如何返回模态的html的例子如下(使用jade作为你的模板引擎,但它可以是任何你喜欢的):

 app.set('view engine', 'jade'); app.get( '/modalFeedback' ,function(req, res, next){ res.render('/modalFeedback.jade', { user: req.user }); } ); 

模板,在这种情况下, modalFeedback.jade将只有HTML,不pipe怎么说,无论如何,这是您希望在模式中显示的html的玉版。 你甚至可以不用简单地渲染模板,首先做一些检查,如果用户是pipe理员或其他。 根据检查,你可以select要渲染的模板。 关键是res.render去获取文件传递你提供的数据,并将返回到模态的浏览器调用。

更新remote从v3.3.0开始已弃用 ,并在v4中删除。 (这可能更适合作为评论,但可能会被忽略,因此将其放在这里以保护人们在后来pipe理向后兼容性问题的时间)

我build议保持空白模式div在HTML ..

 <div id="modalbox" > </div> <button class="btn btn-primary btn-lg" id="modalButton" data-toggle="modal" data-target="#myModal"> Launch demo modal </button> 

调用ajax到服务器,并返回模型框的HTML内容string基于pipe理或其他和填充模式button点击,使模态可见..

 $('#modalButton').click() -> var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET","/modalFeedback",true); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("modalbox").innerHTML=xmlhttp.responseText; } } xmlhttp.send(); $("#modalbox").show();