【问题标题】:Search mysql database with node in html在 html 中使用节点搜索 mysql 数据库
【发布时间】:2018-10-07 20:37:47
【问题描述】:

我将数据库连接到节点并尝试创建一个 HTML 页面来搜索数据库。我宁愿不使用 EJS。我想我必须在 HTML AJAX 中使用 POST 请求并将其与节点中的 POST 请求连接起来。

这是我的想法:

app.post("/cities/:city", function(req, res) {
    db.hospitalinfo.findAll({
        where: { city: req.params.city }
    }).then(function (result) {
        res.json(result);
        console.log("res--->"+result);
        console.log("req--->"+req.params.city);
    });
});

这是 HTML:

<form id="author-form" method="POST">
      <select id ="dropDownId">
          <option value="Opp" >Opp</option>
          <option value="Boaz">Boaz</option>
      </select>
      <input class="SubmitButton" type="submit"  id="click" style="font-size:20px;" />
</form>

现在我遇到了困难。我需要从 select 语句中获取值:

var nameInput = $("#dropDownId :selected");

我不知道如何将 nameInput 实际发送到 URL,因此我的 post 语句将起作用。我可能不完全理解这些路线是如何工作的。这是我自己的第一个项目。我想获取 nameInput,通过 AJAX 将其发送到服务器,然后用它搜索我的数据库。现在它返回一个空对象。感谢您的帮助。

【问题讨论】:

  • 这是一个没有 ExpressJS 的 API 路由示例:stackoverflow.com/questions/45864677/…
  • 我正在使用 express 我只是不想使用像 EJS 这样的后端模板语言,如果我可以避免的话,因为我无法使用它访问 DOM。也许有一种我不知道的方法。

标签: html mysql node.js ajax select


【解决方案1】:

您需要对节点服务器进行 Ajax 调用。为此,您需要停止表单的默认提交。

event.preventDefault();

可用于停止提交表单的正常流程。

这里是一个ajax调用的例子

(document).ready(function() {
    // process the form
    $('form').submit(function(event) {
        // get the form data
        // there are many ways to get this data using jQuery (you can use the class or id also)
        var formData = {
            'name'              : $('input[name=name]').val(),
            'email'             : $('input[name=email]').val(),
        };

        // process the form
        $.ajax({
              type: "GET", // define the type of HTTP verb we want to use (POST for our form)
              url: "http://localhost:5000/example" // the url where we want to POST
              data: formData,
              dataType: 'json', // what type of data do we expect back from the server 
              success: function (data) {
                    console.log(data.result);
                    // perform required changes
                  },
              error: function (err) {
                    console.log(err);
                  }          
               });

        // stop the form from submitting the normal way and refreshing the page
        event.preventDefault();
    });

});

您可以参考这个网站了解更多详情making ajax calls

我已经修改了从那里获取的代码。

【讨论】:

  • 您必须在 ajax 查询中使用 url 传递 nameInput : "localhost:5000/example" + nameInput 并在成功函数中进行更改
猜你喜欢
  • 1970-01-01
  • 2016-05-08
  • 1970-01-01
  • 2019-12-23
  • 1970-01-01
  • 1970-01-01
  • 2014-06-02
  • 1970-01-01
  • 2012-01-25
相关资源
最近更新 更多