Jac*_*ovi 5 ajax jquery node.js elasticsearch mongoosastic
我已经成功配置了mongoosastic,我尝试搜索并且它工作正常,但是当涉及到前端我不确定如何实现这一点时,我尝试了很多方法但是无法想出一个好的解决方案
这是代码.
// For the Search API
router.post('/api/search/', function(req, res, next) {
Job.search(
{
query_string:
{ query: req.body.search }
} , function(err, results) {
if (err) return next(err);
res.json(results);
});
});
Run Code Online (Sandbox Code Playgroud)
因此,每当我搜索与"工程师"相关的内容时,我都会得到一个json数据
所以后端确实完美运行.
但是当涉及到jquery和ajax时,我总是得到不好的请求
逻辑:每当插入某些内容然后发布并找到该结果.
这是前端jquery代码.
$('#search').keyup(function() {
var search_term = $(this).val();
$.ajax({
type: "POST",
url: "/api/search",
success: function(){
$('search_results').html(search_term);
},
error: function(data){
alert('Error', data);
}
});
});
Run Code Online (Sandbox Code Playgroud)
HTML
<input type="text" class="form-control input-lg" id="search" name="search" placeholder="Search for part-time..." />
<div id="search_results">
</div>
Run Code Online (Sandbox Code Playgroud)
如何将json结果插入search_results?
你需要做的是
所以你的前端代码将如下所示:
$('#search').keyup(function() {
// 1. grab the search term from the input field
var search_term = $(this).val();
// 2. send it to your back-end via ajax in the body
$.ajax({
method: "POST",
url: "/api/search", // <-- your back-end endpoint
data: "search=" + search_term // <-- what you're sending
dataType: "json", // <-- what you're expecting back
success: function(json){ // <-- do something with the JSON you get
// 3. parse the JSON and display the results
var res = json.hits.hits.map(function(hit) {
return hit._source.title + ": " + hit._source.salary;
});
$('search_results').html(res.join("<br />"));
},
error: function(data){
alert('Error', data);
}
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
388 次 |
| 最近记录: |