如何使用ejs模板引擎在不重新加载节点js中的整个页面的情况下仅渲染数据

时间:2021-01-30 14:30:37

I'm new to Node JS. Below is my code. On AJAX call new data is not being rendered. Is this the right way to render data without loading the entire page? Is there any better way to load only data without using AJAX.

我是Node JS的新手。以下是我的代码。在AJAX调用中,不会呈现新数据。这是在不加载整个页面的情况下呈现数据的正确方法吗?有没有更好的方法只加载数据而不使用AJAX。

App.js file:

App.js文件:

   app.get('/users', function(req, res) {

         var query = req.query.search;

         User.find({'name' : new RegExp(query, 'i')}, function(err, users){
         var data = {list:users};
         console.log("Searching for "+data);

         res.render('admin/users',{data:data});
    });

 });

Ajax call in ejs file:

在ejs文件中调用Ajax:

<script>
function showResult(str) {

    var xmlHttp = null;
    xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", "/admin/users?search="+str, true );
    xmlHttp.send( null );
    return xmlHttp.responseText;
}
</script>

<input type="text" id="search" name="search" placeholder="Search" class="form-control col-md-7 col-xs-12" onkeyup="showResult(this.value)" >

2 个解决方案

#1


7  

Super simple demo

超级简单的演示

routes.js

routes.js

app.get('/search', searchController.index);
app.get('/search_partial', searchController.partial);

searchController.js

searchController.js

const data = [{ text: 'apple' }, { text: 'potato' }, { text: 'sugar' }];

exports.index = (req, res) => {
  res.render('search/index');
};

exports.partial = (req, res) => {
  const query = req.query.search;
  // emulate mongoose query
  const result = data.filter(item => new RegExp(query, 'i').test(item.text));
  res.render('search/partial', { result });
};

search/index.pug

搜索/ index.pug

extends ../layout

block content
  .page-header
    h3 Search

  form.form-horizontal(onsubmit="searchPartial(this);return false;")
    .form-group
      label(class='col-sm-2 control-label', for='search') Text
      .col-sm-8
        input.form-control(type='text', name='search', id='search', autofocus=true)
    .form-group
      .col-sm-offset-2.col-sm-8
        button.btn.btn-primary(type='submit')
          i.fa.fa-search
          | Find
  #search-result

search/partial.pug

搜索/ partial.pug

.row
  each item in result
    .col-sm-3
      h2=item.text

client-side.js

客户side.js

/* eslint-disable */
$(document).ready(function() {

  // Place JavaScript code here...
  function searchPartial(form) {
    var formData = $(form).serializeArray();
    $.get('/search_partial', {
      search: formData[0].value
    }).then(function (data) {
      $('#search-result').html(data);
    });
  }

  window.searchPartial = searchPartial;
});

This sample should help you, as you can see, we need 2 routes

如您所见,此示例应该可以帮助您,我们需要2条路线

  1. basic route for rendering search index page
  2. 渲染搜索索引页面的基本路线
  3. the partial view that will be populated with data on server, and then appended to DOM in client javascript
  4. 将在服务器上填充数据的局部视图,然后在客户端javascript中附加到DOM

Also recommend you to look at hackaton-starter-kit

还建议你看看hackaton-starter-kit

Result

如何使用ejs模板引擎在不重新加载节点js中的整个页面的情况下仅渲染数据

#2


1  

Your strategy is correct!

你的策略是正确的!

Just need to fix some small things:

只需要修理一些小东西:

  • Routes between server and client should match
  • 服务器和客户端之间的路由应该匹配
  • Ajax API should return data in json format
  • Ajax API应以json格式返回数据

App.js file

App.js文件

app.get('/admin/users', function(req, res) {

         var query = req.query.search;

         User.find({'name' : new RegExp(query, 'i')}, function(err, users){
         var data = {list:users};
         console.log("Searching for "+data);

         res.json({data:data});
    });

});

Hope that it can help :)

希望它可以帮助:)

#1


7  

Super simple demo

超级简单的演示

routes.js

routes.js

app.get('/search', searchController.index);
app.get('/search_partial', searchController.partial);

searchController.js

searchController.js

const data = [{ text: 'apple' }, { text: 'potato' }, { text: 'sugar' }];

exports.index = (req, res) => {
  res.render('search/index');
};

exports.partial = (req, res) => {
  const query = req.query.search;
  // emulate mongoose query
  const result = data.filter(item => new RegExp(query, 'i').test(item.text));
  res.render('search/partial', { result });
};

search/index.pug

搜索/ index.pug

extends ../layout

block content
  .page-header
    h3 Search

  form.form-horizontal(onsubmit="searchPartial(this);return false;")
    .form-group
      label(class='col-sm-2 control-label', for='search') Text
      .col-sm-8
        input.form-control(type='text', name='search', id='search', autofocus=true)
    .form-group
      .col-sm-offset-2.col-sm-8
        button.btn.btn-primary(type='submit')
          i.fa.fa-search
          | Find
  #search-result

search/partial.pug

搜索/ partial.pug

.row
  each item in result
    .col-sm-3
      h2=item.text

client-side.js

客户side.js

/* eslint-disable */
$(document).ready(function() {

  // Place JavaScript code here...
  function searchPartial(form) {
    var formData = $(form).serializeArray();
    $.get('/search_partial', {
      search: formData[0].value
    }).then(function (data) {
      $('#search-result').html(data);
    });
  }

  window.searchPartial = searchPartial;
});

This sample should help you, as you can see, we need 2 routes

如您所见,此示例应该可以帮助您,我们需要2条路线

  1. basic route for rendering search index page
  2. 渲染搜索索引页面的基本路线
  3. the partial view that will be populated with data on server, and then appended to DOM in client javascript
  4. 将在服务器上填充数据的局部视图,然后在客户端javascript中附加到DOM

Also recommend you to look at hackaton-starter-kit

还建议你看看hackaton-starter-kit

Result

如何使用ejs模板引擎在不重新加载节点js中的整个页面的情况下仅渲染数据

#2


1  

Your strategy is correct!

你的策略是正确的!

Just need to fix some small things:

只需要修理一些小东西:

  • Routes between server and client should match
  • 服务器和客户端之间的路由应该匹配
  • Ajax API should return data in json format
  • Ajax API应以json格式返回数据

App.js file

App.js文件

app.get('/admin/users', function(req, res) {

         var query = req.query.search;

         User.find({'name' : new RegExp(query, 'i')}, function(err, users){
         var data = {list:users};
         console.log("Searching for "+data);

         res.json({data:data});
    });

});

Hope that it can help :)

希望它可以帮助:)