如何使用JavaScript运行MySQL查询

8

我希望能够在不重新加载页面的情况下运行MySQL查询。我认为JavaScript可以实现这一点,但我不确定如何操作。我的想法是创建一个表单,其中包含一个返回ID字段,当您填写一次表单并稍后再次使用该返回ID时,它会自动填充大量内容以节省时间。


可能是重复的问题:如何使用JavaScript查询数据库? - Thilo
6个回答

8

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

以下是jquery的ajax()方法的示例:

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

我已经发布了代码作为示例,但是如果不知道您使用的服务端语言,我无法给您提供更多细节。 - Josh Mein

7

您无法使用纯JavaScript进行查询,必须通过在后端设置的钩子来完成。

通常会使用ajax完成此操作。

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


3
使用ajax即可完成该任务。但仍需要一种服务器端语言供ajax调用。 使用jquery与ajax结合,效率更高!
$.ajax({
  type: "POST",
  url: "someserversidelangfile",
  data: "" //pass data through this variable
}).done(function( msg ) {
  //do so
});

PHP不是唯一的服务器端技术。 - Travis J
非常正确。我会进行编辑以显示还有其他选项。 :) - transparent
尽管OP刚刚表示他们正在使用PHP,因此考虑到这一点,也许你应该在这里提供更多关于PHP的信息:D - Travis J

3

您需要编写后端脚本来执行查询 - JavaScript是一种完全客户端语言,无法控制MySQL服务器的运行情况。

您需要通过AJAX将要查询的参数传递给您正在使用的任何服务器端语言,并让脚本按照您的意愿创建和处理查询。

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


1

现在大家都在讨论ajax,以下是一个使用纯JavaScript发送数据并获取响应的示例。这将是一个无意义的示例,并使用非PDO MySQL连接。后端是PHP,但script.js文件对于NODE.js后端实际上是相同的。

script.js


/* mode options are cors, no-cors (only send, no response) and same-origin */
fetch('not-ajax.php', {
  method: 'post',
  mode: 'same-origin',
  credentials: 'same-origin',
  headers: {
    'Content-Type': 'application/json',  // sent request
    'Accept':       'application/json'   // expected data sent back
  },
  body: JSON.stringify({
    /**
     * FYI: For this particular case you would actually prefer to have this snippet
     * just before ending </body> tag so it get's actual width of the window minus
     * the width of the scrollbar if there is one. If you use it in an external
     * script it's the same as using window.innerWidth and window.innerHeight.
     **/
    'screen_width': document.documentElement.clientWidth,
    'screen_height': document.documentElement.clientHeight
  })
})
/**
 * You need this part as well if you send json-encoded data back from backend.
 **/
.then(response => response.json())
.then(data => {
  console.log('Success:', data);
})
.catch((error) => {
  console.error('Error:', error);
});

not-ajax.php

<?php
  include 'connection.php';

  $contentType = isset($_SERVER["CONTENT_TYPE"]) ? trim($_SERVER["CONTENT_TYPE"]) : '';
  if ($contentType === "application/json") {

    // Receive the RAW post data.
    $content = trim(file_get_contents("php://input"));
    // $decoded can be used the same as you would use $_POST with ajax
    $decoded = json_decode($content, true);

    /**
     * Sure enough you can use a SELECT statement, get the data from the database,
     * manipulate it to your heart's content, and then send it back to fetch
     * function in JavaScript for further manipulation and usage.
     **/
    $sql =
      "INSERT INTO used_screen_dimensions (
      ) VALUES ( ?, ? )";
    $statement = $connection->prepare($sql);
    /**
     * first parameter is a string with characters
     *   'i' for integer,
     *   'd' for double,
     *   's' for string,
     *   'b' for blob
     * in the respective order to all other binded parameters
     **/
    $statement->bind_param('ii', $decoded['screen_width'], $decoded['screen_height']);
    $result = $statement->get_result();
    $statement->close();

    /**
     * You may only echo out one thing, but it doesn't have to be a boolean.
     * You can (and should) echo an object with more info including what error
     * it is.
     **/
    if(! is_array($decoded)) {
      echo 0; //If json_decode failed, the JSON is invalid.
      return;
    } else {
      // Send error back to fetch.
      if (!$result) {
        echo 0; // couldn't insert to database
        return;
      }
      echo 1; // Success
    }
  } else {
    echo 0; // Wrong content type
  }

我不知道为什么要手动输入这个答案。肯定会有错误。


-1

JavaScript 无法运行 MySql 命令。您可以使用 JQuery 和 Ajax,例如:

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


1
请在您的回答中提供更多细节。目前的写法让人难以理解您的解决方案。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接