从 javascript/AJAX 调用 MySQL 查询
Posted
技术标签:
【中文标题】从 javascript/AJAX 调用 MySQL 查询【英文标题】:Call MySQL query from javascript/AJAX 【发布时间】:2014-04-07 22:04:15 【问题描述】:我有一个日历函数,我需要从我的 mysql 数据库中调用一个函数。系统功能如下:您可以选择“开始”日期-“结束”日期。它看起来像这样:
http://postimg.org/image/5uurc5ycb/
javascript/AJAX 代码有效并且成功连接到我的数据库。所以我想做的是调用查询:
SELECT *, (Day_hours + (Day_minutes / 100)) as Allday_hours FROM Workdata
因此它将返回 Allday_hours 列。有谁知道我该怎么做?最好的问候疯子
<form>
<input id="start1" />
<input id="start2" />
</form>
<script>
$(function()
$("#start1").datepicker(
dateFormat: 'yy-mm-dd',
onSelect: function(dateText,inst)
alert(dateText);
$.ajax(
url: "../dataExchange",
type: "post",
data: Date,
success: function()
alert("success");
$("#result").html('submitted successfully');
,
error:function()
alert("failure");
$("#result").html('there is error while submit');
);
);
);
$(function()
$("#start2").datepicker(
dateFormat: 'yy-mm-dd',
onSelect: function(dateText,inst)
alert(dateText);
$.ajax(
url: "../dataExchange",
type: "post",
data: Date,
success: function()
alert("success");
$("#result").html('submitted successfully');
,
error:function()
alert("failure");
$("#result").html('there is error while submit');
);
);
);
</script>
我与数据库的连接是通过一个 servlet,如下所示:
package WorkPackage;
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
@WebServlet("/dataExchange")
public class dataExchange extends HttpServlet
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
doPost(request, response);
public void init(ServletConfig config) throws ServletException
super.init(config);
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
String connectionURL = "jdbc:mysql://localhost/NekiWork";
Connection connection=null;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String Date = req.getParameter("Date");
String Name = req.getParameter("Name");
String Address = req.getParameter("Address");
String Day_hours = req.getParameter("Day_hours");
String Day_minutes = req.getParameter("Day_minutes");
String Km_to_address = req.getParameter("Km_to_address");
String Time_to_address = req.getParameter("Time_to_address");
try
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(connectionURL, "root", "");
String sql = "INSERT INTO Workdata (Date, Name, Address, Day_hours, Day_minutes, Km_to_address, Time_to_address) VALUES (?,?,?,?,?,?,?)";
PreparedStatement pst = connection.prepareStatement(sql);
pst.setString(1, Date);
pst.setString(2, Name);
pst.setString(3, Address);
pst.setString(4, Day_hours);
pst.setString(5, Day_minutes);
pst.setString(6, Km_to_address);
pst.setString(7, Time_to_address);
pst.executeUpdate();
pst.close();
catch(ClassNotFoundException e)
out.println("Couldn't load database driver: " + e.getMessage());
catch(SQLException e)
out.println("SQLException caught: " + e.getMessage());
catch (Exception e)
out.println(e);
finally
try
if (connection != null) connection.close();
catch (SQLException ignored)
out.println(ignored);
【问题讨论】:
javascript 无法直接连接 MySQL !?!? 我已经编辑了我的问题。我忘了写我的连接是通过一个 servlet 进行的:-/ 我想我不确定你在哪里被挂断了。通过查看您的 servlet,您似乎已经知道如何对数据库进行查询。是什么阻止您简单地对数据库运行所需的查询?换句话说,当您尝试此操作时遇到的具体问题是什么? 你好迈克。非常感谢您的回答。我的问题是我不知道在哪里放置:SELECT *, (Day_hours + (Day_minutes / 100)) as Allday_hours FROM Workdata。当我选择我的日期时,应该执行该查询。 最好改用JSON。 【参考方案1】:我对 servlet 没有太多经验,但基本上,您可以像这样指定 ajax 应该执行的操作:
$.ajax(
url: "../dataExchange",
type: "post",
data: date: Date, action: "doTheSelect",
dataType: 'json',
success: function(data)
alert("success");
$("#result").html('submitted successfully');
// do something with variable - data(returned json object)
,
error:function()
alert("failure");
$("#result").html('there is error while submit');
);
并在您的 servlet 中指定这样的 if 条件(伪代码):
if(posted_data.action == "doTheSelect")
// here goes the SQL query
return "json encoded result of query";
else
// do some other stuff like specifying another condition based on another value of action variable
因此只执行提到的查询。最后就可以在 ajax.success 函数中处理接收到的数据了。
【讨论】:
以上是关于从 javascript/AJAX 调用 MySQL 查询的主要内容,如果未能解决你的问题,请参考以下文章
如何在 JavaScript ajax 调用中从 PHP passthru 获取二进制数据?
JavaScript AJAX 调用中的安全 REST API 令牌