简体   繁体   English

如何使用javascript和node.js-mysql而不使用php将HTML表单数据提交到MySql数据库表中?

[英]How can I submit HTML form data into MySql database table using javascript along with node.js - mysql and without php?

I was trying to make a blog where a viewer(guest) can send message to the blogger.我试图制作一个博客,观众(客人)可以向博主发送消息。 HTML form prepared and in onclick() function of the Submit button of the HTML form, a javascript (named Db_connect.js) function named submitData() is executed.准备好 HTML 表单,在 HTML 表单的提交按钮的 onclick() 函数中,执行名为 submitData() 的 javascript(名为 Db_connect.js)函数。 In submitData(), two more functions are called from the same javascript - one to establish connection with mysql and another to execute mysql query to insert data in a database to store form data.在 submitData() 中,同一个 javascript 调用了另外两个函数 - 一个用于与 mysql 建立连接,另一个用于执行 mysql 查询以在数据库中插入数据以存储表单数据。 Another function called named openWin(), is nothing but to display the content inserted in a seperate new small window.另一个名为 openWin() 的函数只不过是显示插入到单独的新小窗口中的内容。

This is the javascript Code that I am using to connect to databse:这是我用来连接到数据库的 javascript 代码:

var con, sql;
function randomNumber(min, max) {  
    return Math.floor(Math.random()* (max - min) + min); 
}  

function submitData(objButton) {
    name = document.getElementById('name1').value; 
    email = document.getElementById('email1').value; 
    msg = document.getElementById('msg1').value; 
    i= randomNumber(1000000000000000,9999999999999999);
    document.getElementById('test').innerHTML=name;
    sql="INSERT INTO my_table(id, name, email, msg) VALUES(" + i + ", '" + name + "', '" + email + "', '" + msg +  "')";
    createConnection();
    insertData(sql);
    openWin();
}

var mysql = require('mysql');
function createConnection() {
      con = mysql.createConnection({
      host: "localhost",
      user: "username",
      password: "password",
      database: "mydb"
    });
}

function insertData(sql_insert) {
    con.connect(function(err) {
      if (err) throw err;
       con.query(sql_insert, function (err) {
        if (err) throw err;
        });
    });
}

function openWin(){
      var myBars = 'directories=no,location=no,menubar=no,status=no';
      myBars += ',titlebar=no,toolbar=no';
      var myOptions = 'scrollbars=no,width=400,height=200,resizeable=no';
      var myFeatures = myBars + ',' + myOptions;
      var newWin = open('', 'myWin', myFeatures);
      newWin.document.writeln('<form>');
      newWin.document.writeln('<table>');
      newWin.document.writeln('<tr><td>Your Message Sent...');
      newWin.document.writeln('</td></tr>');
      newWin.document.writeln('<tr valign=TOP><td>');
      newWin.document.writeln('<textarea cols=45 rows=7 wrap=SOFT>');
      newWin.document.writeln('Your Name : '+name);
      newWin.document.writeln('Your Email : '+email);
      newWin.document.writeln('Your Message : '+msg);
      newWin.document.writeln('Data Inserted!!!</textarea>');
      newWin.document.writeln('</td></tr>');
      newWin.document.writeln('<tr><td>');
      newWin.document.writeln('<input type=BUTTON value="Close"');
      newWin.document.writeln(' onClick="window.close()">');
      newWin.document.writeln('</td></tr>');
      newWin.document.writeln('</table></form>');
      newWin.document.close();
      newWin.focus();
}

And this is the HTML code I am using :这是我正在使用的 HTML 代码:

<head>
        <script src="Db_Connect.js" type="text/javascript"></script>
   </head>
<body>

        <script type="text/javascript"></script>
        <div id="frm">
            <form>
                <label id="name"> <b>Your Name &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;: </b></label><input id="name1" type="text" name="user_name" placeholder="Your Name." required><label style="color:red; font-size:18px;"><b>&nbsp;*</b></label><br><br>  <!--placeholder="Your Name."-->
                <label id="email"><b>Your E-mail &nbsp;&nbsp;&nbsp;&nbsp;: </b></label><input id="email1" type="email" name="user_email" placeholder="Your Email ID." required><label style="color:red; font-size:18px;"><b>&nbsp;*</b></label><br><br>  <!--placeholder="Your Email ID."-->
                <label id="msg">  <b>Your Message : </b></label><textarea id="msg1" name="user_msg" maxlength="200" placeholder="Maximum 200 letters." required></textarea><label style="color:red; font-size:18px;"><b>&nbsp;*</b></label><br>             <!--<span id="send"><a id="link" href="http://www.google.co.in" target="_blank"><b>Send</b></a></span>-->
                <label style="color:red;font-size:10px;"><b>* Required fields</b></label><br>
                <input type="submit" id="link" value="Send" onclick="submitData(this)">    <!--onclick="submitData(this)"-->
            </form>
        </div>
</body>

The same javascript without data input from HTML is working fine from Console.没有来自 HTML 的数据输入的相同 javascript 在控制台中工作正常。 But, with HTML form data passed to it, it is not working at all.但是,通过传递给它的 HTML 表单数据,它根本不起作用。 Note that, I am not using php and don't want to use it.请注意,我没有使用 php,也不想使用它。 Please help me to get rid of the problem and provide me some solution to it without use of php.请帮助我摆脱这个问题,并在不使用 php 的情况下为我提供一些解决方案。

You have to create web server with node.js and express.js and then get the data from HTML FORM POST.您必须使用node.jsexpress.js创建 Web 服务器,然后从 HTML FORM POST 获取数据。 Follow link and code example.按照链接和代码示例。

https://www.tutorialsteacher.com/nodejs/expressjs-web-application https://www.tutorialsteacher.com/nodejs/expressjs-web-application

Handle POST Request处理 POST 请求

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <form action="/submit-student-data" method="post">
        First Name: <input name="firstName" type="text" /> <br />
        Last Name: <input name="lastName" type="text" /> <br />
        <input type="submit" />
    </form>
</body>
</html>

var express = require('express');
var app = express();

var bodyParser = require("body-parser");
app.use(bodyParser.urlencoded({ extended: false }));

app.get('/', function (req, res) {
    res.sendFile('index.html');
});

app.post('/submit-student-data', function (req, res) {
    var name = req.body.firstName + ' ' + req.body.lastName;
    
    res.send(name + ' Submitted Successfully!');
});

var server = app.listen(5000, function () {
    console.log('Node server is running..');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 node.js 和 JavaScript 从 HTML 简单表单插入 INTO MySQL 表 - Insert INTO MySQL Table from HTML simple form using node.js and JavaScript 使用node.js将表格数据插入mysql数据库表并进行序列化 - Insert form data into mysql database table using node.js and sequelize 如何使用mysql数据库在node.js中创建登录表单 - How to make login form in node.js using mysql database Node.js / jade —如何将mysql数据作为局部变量传递给内联javascript? - Node.js/jade — How can I pass mysql data as a local variable into inline javascript? 如何使用 JavaScript 和 Node.Js 在 Fusion Chart 上传递 MySQL 数据? - How do I pass MySQL data on Fusion Chart using JavaScript and Node.Js? Node.js将mysql数据发送到HTML表解析问题 - Node.js send mysql data to HTML table parse problem 嘿,当使用 node.js 从 html 表单将数据插入 MySql 时,我不知道从哪里开始 - Hey I don't know where to start when inserting data into MySql from html form using node.js 我想在输入框、表格或使用 node.js 的 div 文件中显示存储在 mysql 数据库中的数据。 - I want to display data stored in mysql database in .html file on input boxes,tables,or in a div using node.js 在带有 Node.js 的 html 表中显示 mysql - Display mysql in a html table with Node.js 使用Node.js将表单数据发布到MySQL - Post Form data to MySQL using Node.js
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM