有没有办法让Node使用JSON重定向到新页面?

时间:2019-05-13 01:14:18

标签: javascript node.js

我正试图允许用户在index.html页面上的框中键入搜索查询,并将其发送到显示结果的results.html页面。

目前,我只能在index.html页面上执行此操作,在该页面上,旧的HTML已被删除并替换为搜索结果。

//Pertinent Node code:

    app.get('/', function(req, res){
    res.header("Access-Control-Allow-Origin", "*");

    res.redirect('index.html');

});

// A search box in index.html calls the /search below

app.get('/search', function (req, res) {
    res.header("Access-Control-Allow-Origin", "*");
    const item_id = req.query.item_id;
    var json = {};

    var sql_query = "a SQL query";

    var result = connection.query(sql_query, function(err, result,         fields) {
        if (err) throw err;
        json["result"] = result;

        console.log("Sent JSON to client");
        res.send(JSON.stringify(json));
    });
})

//Client-side:
    function get() {
        var search = document.getElementById("search").value;

        // Validate input to prevent injections
        var new_search = search.replace("<", "");
        var validated = new_search.replace(">", "");

        var url = host + "/search?search=" + validated;

        fetch(url, {method : 'GET'})

            .then(checkStatus)
            .then(function(responseText) {
                var json = JSON.parse(responseText);
                displaySearchResults(json, search);
            })

            .catch(function(error) {
            });
    }

我要尝试的操作类似于您在Google上看到的内容,单击搜索将您发送到一个新页面,该页面的网址为:“ https://www.google.com/searchresults?query=bicycles”,该网址显示的是与index.html不同的HTML页面(例如results.html),并将index.html中的JSON移至results.html中并在中进行处理。

我如何做到这一点?

1 个答案:

答案 0 :(得分:0)

为布拉德在评论中所提及的内容添加一些细节。完整的解决方案是:

<form action="search.html" method="GET" name="search">

然后在search.html的Javascript文件中,使用以下命令访问表单数据:

var search = window.location.search;

如果您需要从数据中获取“?search =“,请使用:

var search = window.location.search.replace("?search=", "");