如何使用ajax和节点从表单获取请求

时间:2017-12-20 20:43:44

标签: javascript node.js ajax

我正在使用Node.js和我的Web应用程序的快速框架。我想要做的是在点击一下按钮后从客户端获取输入( index.js )并从我的路径( app.js )请求信息关闭该参数以显示在我的索引页面上。我尝试使用ajax向我的路线发出请求,但它不起作用。我知道我在使用URL查询字符串做错了,但不太确定如何修复它。如果我需要澄清更多信息,请告诉我。提前致谢。

index.ejs

<form action="" id="searchForm">
    <!-- Input box-->
    <input type="text" id="userName" name="userName">
    <!-- Submit button-->
    <input type="submit" value="Click Me">
</form>

的script.js

$(document).ready(function () {    
// When the search Button is clicked run function
$("#searchForm").submit(function () {
    // Make a ajax request to a route
    $.ajax({
        // Connect to /json route
        url: "http://localhost:8080/json",
        contentType: "application/json",
        dataType: 'json',
        // If there is no errors run my function
        success: function (data) {
            //Writes the data to a table
            var table = "";
            for (var i in data) {
                table += "<tr><td>" + data[i] + "</td></tr>";
            }
        },
        // If there is any errors, show me.
        error: function () {
            alert('Oops, there seems to be an error!');
        },
        type: "GET",
    });           
});
});

routes.js

module.exports = function (app){
    app.get('/', function (req, res) {
        res.render('index.ejs'); //load the page
    });

app.get('/json', function (req, res) {
        var SomeQuery = "SELECT * FROM table WHERE user LIKE '%" + req.query.userName+ "%';
        client.query(SomeQuery, function (err, results) {
            if (err) throw err; //Show any errors
            var data = [];
            // Loop through all known data
            for (var i = 0; i < results.rows.length; i++) {
                data.push(results.rows[i]); //Push any information into empty array
            }
            res.json(data); //send it to make an ajax request
        });
    });
});
}

解决方案 对于遇到同样问题的人来说,修复:

的script.js

$(document).ready(function () {    
// When the search Button is clicked run function
$("#searchForm").submit(function () {
    // Make a ajax request to a route
    //Value from input
    var userNameID = $("#username").val();
    $.ajax({
        // Connect to /json route
        url: "http://localhost:8080/json?userName=" + userNameID,
        contentType: "application/json",
        dataType: 'json',
        // If there is no errors run my function
        success: function (data) {
            //Writes the data to a table
            var table = "";
            for (var i in data) {
                table += "<tr><td>" + data[i] + "</td></tr>";
            }
        },
        // If there is any errors, show me.
        error: function () {
            alert('Oops, there seems to be an error!');
        },
        type: "GET",
    });           
});
});

1 个答案:

答案 0 :(得分:2)

问题是,您使用输入类型提交。提交realod页面并显示发回的内容。有几种方法可以解决它。

  1. 第一种解决方法,将提交类型更改为简单按钮类型。
  2. 第二种方法是使用event.preventDefault()

    停止默认浏览器行为
    `$(document).ready(function () {    
    // When the search Button is clicked run function
    $("#searchForm").submit(function (event) {
      // Make a ajax request to a route
      $.ajax({
        // Connect to /json route
        url: "http://localhost:8080/json",
        contentType: "application/json",
        dataType: 'json',
        // If there is no errors run my function
        success: function (data) {
            //Writes the data to a table
            var table = "";
            for (var i in data) {
                table += "<tr><td>" + data[i] + "</td></tr>";
            }
        },
        // If there is any errors, show me.
        error: function () {
            alert('Oops, there seems to be an error!');
        },
        type: "GET",
      });   
      event.preventDefault()       
     });
    });`