gpt4 book ai didi

javascript - 如何通过 AJAX 调用将输入字段值发送到 Node JS 后端以实现预输入功能

转载 作者:行者123 更新时间:2023-12-03 01:06:35 25 4
gpt4 key购买 nike

我正在尝试实现如下所示的预输入功能。

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>
...
...

我的后端node 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
});

现在,每当我尝试在“产品”文本字段中输入内容时,它都会调用后端/search api。然而,我无法捕捉到产品领域的值(value)。

任何帮助将不胜感激?请注意,我需要使用 ajax 调用来将输入文本值发送到后端的输入功能。

三个控制台日志的输出如下...

Search string >> [object Object]
Search string >> {}
Search string >> undefined

最佳答案

express 不会解析它自己提供给 API 的输入。因此,我们需要一些额外的工具,例如 body-parser 来从请求中获取输入并将其格式化为 JSON。这也可以在没有 body-parser 的情况下完成。

请仔细阅读此内容 documentation它涵盖了很多内容。

  1. 使用body-parser,您需要使用express设置body-parser:

```

const bodyParser                  = require('body-parser'),
// For Cross-Origin Resource Sharing
CORS = require('cors'),
express = require('express');

const app = express();

// Cross-Origin Resource Sharing
app.use(CORS());

// configure the app to use bodyParser() to extract body from request.
// parse urlencoded types to JSON
app.use(bodyParser.urlencoded({
extended: true
}));

// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }));

// parse some custom thing into a Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }));

// parse an HTML body into a string
app.use(bodyParser.text({ type: 'text/html' }));


// This will get you input at `req.body`

app.post('/search',(req,res)=>{
console.log(JSON.stringify(req.body));
});

```

  • 不使用body-parser:
  • ```

    app.post('/', (req, res, next) => {

    let body = [];

    req.on('error', (err) => {
    console.error(err);
    }).on('data', (chunk) => {
    // Without parsing data it's present in chunks.
    body.push(chunk);
    }).on('end', () => {
    // Finally converting data into readable form
    body = Buffer.concat(body).toString();

    console.log(body);

    // Setting input back into request, just same what body-parser do.
    req.body = body;
    next();
    });

    }, (req, res) => {
    console.log(req.body);
    });

    ```

    关于javascript - 如何通过 AJAX 调用将输入字段值发送到 Node JS 后端以实现预输入功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52371822/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com