我是Node JS的新手。以下是我的代码。在AJAX调用中,不会呈现新数据。这是在不加载整个页面的情况下呈现数据的正确方法吗?有没有更好的方法只加载数据而不使用AJAX。
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});
});
});
在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)" >
答案 0 :(得分:8)
超级简单的演示
<强> routes.js 强>
app.get('/search', searchController.index);
app.get('/search_partial', searchController.partial);
<强> 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 });
};
搜索/ 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
搜索/ partial.pug 强>
.row
each item in result
.col-sm-3
h2=item.text
<强>客户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;
});
如您所见,此示例应该可以帮助您,我们需要2条路线
还建议您查看hackaton-starter-kit
答案 1 :(得分:2)
你的策略是正确的!
只需修理一些小东西:
server
和client
之间的路由应匹配json
格式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});
});
});
希望它可以提供帮助:)