如何使用 JavaScript 运行 MySQL 查询

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11217832/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:57:46  来源:igfitidea点击:

how to run a MySQL query using JavaScript

javascriptmysql

提问by jardane

I want to run MySQL query's on command without reloading the page. I think JavaScript can do this but i am unsure how. What i want to do is have a form with an return id field and when you fill out the form once with the return id and come back later and use that return id and it fills in in a lot of the content for them to save time.

我想在不重新加载页面的情况下运行 MySQL 查询的命令。我认为 JavaScript 可以做到这一点,但我不确定如何做到。我想要做的是有一个带有返回 id 字段的表单,当您使用返回 id 填写一次表单并稍后返回并使用该返回 id 时,它会为他们填写很多内容以节省时间.

采纳答案by Josh Mein

Javascript cannot run MySQL Queries itself; however, you can use ajaxto make a call to the server to retrieve the data. I like to use jQuery's ajax()for my ajax needs.

Javascript 不能运行 MySQL 查询本身;但是,您可以使用ajax调用服务器来检索数据。我喜欢使用 jQuery 的ajax()来满足我的 ajax 需求。

Here is an example of how jquery's ajax() method works:

下面是 jquery 的 ajax() 方法如何工作的一个例子:

$.ajax({
  url: "pathToServerFile",
  type: "POST",
  data: yourParams,
  dataType: "json"
});

回答by Travis J

You can't query with pure javascript. It has to be done from a hook that is setup on a backend.

您不能使用纯 javascript 进行查询。它必须通过在后端设置的钩子来完成。

This tends to be done with ajax.

这往往是用 ajax 来完成的。

Moreover, if querying were available from client side, then everyone could see your connection string.

此外,如果可以从客户端进行查询,那么每个人都可以看到您的连接字符串。

回答by Sean Johnson

You'll need to have a backend script do the query - JavaScript, being an entirely client-side language, has no say-so in what goes on with your MySQL server.

您需要有一个后端脚本来执行查询 - JavaScript 作为一种完全客户端语言,对 MySQL 服务器的运行情况没有任何发言权。

What you'll need to do is pass the parameters you want in your query to whatever server-side language you're using via AJAX, and have the script create and process the query as you wish.

您需要做的是通过 AJAX 将查询中所需的参数传递给您使用的任何服务器端语言,然后让脚本根据需要创建和处理查询。

DO NOT create the query in javascript and pass it to the server - this is VERY unsafe as it allows anyone to run whatever queries they want.

不要在 javascript 中创建查询并将其传递给服务器 - 这是非常不安全的,因为它允许任何人运行他们想要的任何查询。

回答by transparent

Using ajax will do the job. But you'll still need a server-side language for the ajax to call to. Using jquery with ajax will be even quicker!

使用 ajax 将完成这项工作。但是您仍然需要一种服务器端语言供 ajax 调用。使用 jquery 和 ajax 会更快!

$.ajax({
  type: "POST",
  url: "someserversidelangfile",
  data: "" //pass data through this variable
}).done(function( msg ) {
  //do so
});