Ajax,带有Express的NodeJS,Javascript [英] Ajax,NodeJS with Express ,Javascript
问题描述
我正在使用nodejs,html,express,node-nosql和JavaScript.我在 html页面在下面给出时遇到问题:
I am using nodejs ,html,express , node-nosql and JavaScript. I have a problem wherin the html page is given below :
<body>
<form name="form1" method="post" onSubmit="createTable();return myFunction();">
<input type ="text" name="DomainName" id="Domain_name" required="" />
<input type="submit" value="Submit" />
</form>
<form name="form2" action="http://www.cs.tut.fi/cgi-bin/run/~jkorpela/echo.cgi" method="post">
<div id="table_container"></div>
<input type="submit" value="submit" />
</form>
</body>
javascript函数如下:
function myFunction() {
var input_domain = document.forms["form1"]["DomainName"].value;
if (input_domain == null || input_domain == "") {
alert("Please enter a valid domain");
return;
}
return false;
}
function createTable() {
document.getElementById("table_container").innerHTML = "";
var input_domain = document.forms["form1"]["DomainName"].value;
if (input_domain == null || input_domain == "") return;
var names = ["website1", "website2"];
var table = document.createElement("table"),
...using javascript dynamically create a table with certain columns for each of the websites listed in the var names list ...
document.getElementById("table_container").appendChild(table);
</script>
我现在面临的问题是,当我单击form1的提交按钮时,
变量名称= ["website1","website2"];
必须从数据库中检索.我知道我必须将ajaxrequest与nodejs一起使用.但是我不知道如何退还和处理它!请帮忙.
The Problem i am facing now is , when i click on submit button of form1 , the
var names = ["website1", "website2"];
has to be retrieved from database . I know i have to use the ajaxrequest with nodejs. But i am at a loss as to how it should be returned and processed ! Please help .
推荐答案
评论您作为注释添加的nodejs代码
Commenting on the nodejs code you put as comment
ajax请求的快速路由可以这样
the express route for ajax request could be made like
/** include these require and connect lines if you already dont have it in the code **/
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
});
connection.connect();
/** express route for ajax request starts **/
$.post("/ajaxTarget",function(data){
connection.query('SELECT DBName FROM CrawlerDBInfo where Domain =' + "' " + input_domain + " '" + ';', function (error, rows, fields) {
if (rows.length == 0) {
res.json({error:"no record!!"});
} else {
res.json({data:rows});
}
}
});
注释:
- 您正在使用express,因此您可以直接使用
res.json
发送json响应. - 不需要遍历数组并构建json结果.
- 还要确保您将最初的mysql require&连接代码中的行.
- 还考虑使用mysql查询回调中可用的
error
对象.
- you are using express, so you can directly use
res.json
for sending the json response. - no need of looping over the array and building the json result.
- also make sure you put the initial mysql require & connect lines in the code.
- also think of using the
error
object available in your mysql query callback.
这篇关于Ajax,带有Express的NodeJS,Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!