Я пытаюсь реализовать функциональность typeahead, как показано ниже.
HTML-страница
...
...
<input id="product" name="product" type="text" class="form-control" placeholder="Enter Product Name" autocomplete="off">
...
...
<script>
$(document).ready(function () {
fetchTypeAheadResult();
});
function fetchTypeAheadResult() {
$('#product').typeahead({
source: function (request, response) {
var formData = {
'product' : $('#product').val()
}
// var formData = $('form').serialize();
$.ajax({
url: "/search",
dataType: "json",
type: "POST",
data: formData,
contentType: "application/json; charset=utf-8",
success: function (result) {
var items = [];
response($.map(result, function (item) {
items.push(item.name);
}))
response(items);
// SET THE WIDTH AND HEIGHT OF UI AS "auto" ALONG WITH FONT.
// YOU CAN CUSTOMIZE ITS PROPERTIES.
$(".dropdown-menu").css("width", "100%");
$(".dropdown-menu").css("height", "auto");
$(".dropdown-menu").css("font", "12px Verdana");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
},
hint: true, // SHOW HINT (DEFAULT IS "true").
highlight: true, // HIGHLIGHT (SET <strong> or <b> BOLD). DEFAULT IS "true".
minLength: 1 // MINIMUM 1 CHARACTER TO START WITH.
});
}
</script>
...
...
А мой бэкэнд код узла js выглядит следующим образом
'use strict';
const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');
const app = express();
// configure the app to use bodyParser() to extract body from request.
app.use(bodyParser.urlencoded({ extended: true }));
// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }));
app.post('/search', (req, res) => {
let searchText = req.body;
console.log('Search string >> ' + req);
console.log('Search string >> ' + JSON.stringify(req.body));
console.log('Search string >> ' + req.body.product);
// Not correct, but still trying if it works
// var result = triestrct.get(req.body.product);
res.send({test:'text'}); // TODO - to be updated with correct json
});
Теперь, когда я пытаюсь набрать текстовое поле «product», оно вызывает интерфейс back / search. Однако я не могу уловить значение поля продукта.
Любая помощь будет оценена? Обратите внимание, мне нужна функциональность typeahed с вызовом ajax для отправки входного текстового значения на сервер.
Вывести из трех консольных журналов следующим образом ...
Search string >> [object Object]
Search string >> {}
Search string >> undefined