简体   繁体   English

如何使用 AJAX 从数据库中检索数据并将结果保存在变量中?

[英]How can I retrieve data from a database using AJAX and save the results in a variable?

I'm new to jQuery and AJAX and I'm working on a login-page as a project and I need to retrieve data from a database using AJAX.我是 jQuery 和 AJAX 的新手,我正在作为一个项目在登录页面上工作,我需要使用 AJAX 从数据库中检索数据。 I'm not 100% fluent in English so I'll do my best to explain the problem (with help from Google Translate).我的英语不是 100% 流利,所以我会尽力解释这个问题(在谷歌翻译的帮助下)。 Here's the code I'm using:这是我正在使用的代码:

index.html索引.html

<!DOCTYPE html>
<html>
  <head>
  <title>Login</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  </head>
  <body>
    <form validate="">
      <input type="text" placeholder="Username" id="username" required/><br />
      <input type="password" placeholder="Password" id="password" required/><br />
      <input type="submit" id="submit" value="Login" />
    </form>
    <script type="text/javascript">
    // when document is loaded
    $(document).ready (
      // when submit is clicked
      $("#submit").click (
        // sets test to null
        var test = null;
        // sets username to value of username input
        var username = document.getElementById("username").value;
        // AJAX request 
        $.ajax({
          type: "POST",
          async: true,
          url: test.php,
          data: {username: username},
          success: function (data) {
            test = data;
            console.log(test);
            return test;
          }
        });
      );
    );
    </script>
  </body>
</html>

test.php测试文件

<?php
// connects to database
$conn = mysqli_connect('server', 'username', 'password', 'database');

// sets var username to POST username value
$username = $_POST['username'];

// SQL Query
$sql = "SELECT * FROM users WHERE username='" . $username . "'";
$result = mysqli_query($conn, $sql);

// sets result to mysqli_fetch_assoc()
$result = mysqli_fetch_assoc( $result );

// echos $result
echo $result['password'];

// closes database connection
mysqli_close( $conn );
?>

Console Log控制台日志

Console Output: ``` [DOM] Input elements should have autocomplete attributes (suggested: "current-password"): (More info: https://www.googlesite.com ) ​控制台输出:``` [DOM] 输入元素应具有自动完成属性(建议:“当前密码”):(更多信息: https : //www.googlesite.com

Uncaught SyntaxError: Unexpected token var ajax.html:19未捕获的语法错误:意外的令牌 var ajax.html:19

I've looked at the code and I can't seem to find an error.
Thanks in advance! ;)

>P.S.
>It's probably going to end up being some stupid typo.
>Other than that, have a great day!

You need to pass in a function to your document.ready() call and your click() call.您需要将函数传递给 document.ready() 调用和 click() 调用。

     <script type="text/javascript">

        $(document).ready(function() {
            Your variables here...

            $('#submit').click(function() {
                ... Ajax call here.
            });
        });
    </script>

Instead of using click event you can use submit .您可以使用submit代替click事件。

In your case, just give id to your form like -在您的情况下,只需为您的form提供id ,例如 -

<form validate="" id="submit">

Now, In your js script -现在,在你的js脚本中 -

$(function() { //shorthand document.ready function
    $('#submit').on('submit', function(e) { 
        e.preventDefault();  //prevent form from submitting
        console.log(data);
        $.ajax({
          type: "POST",
          async: true,
          url: test.php,
          data: $(this).serializeArray(),
          success: function (data) {
            console.log(data);
          }
        });
    });
});

So check your whole code -所以检查你的整个代码 -

<!DOCTYPE html>
<html>
  <head>
  <title>Login</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  </head>
  <body>
    <form validate="" id="submit">
      <input type="text" placeholder="Username" id="username" required/><br />
      <input type="password" placeholder="Password" id="password" required/><br />
      <input type="submit" value="Login" />
    </form>
    <script type="text/javascript">
    // when document is loaded
    $(function() { //shorthand document.ready function
    $('#submit').on('submit', function(e) { 
        e.preventDefault();  //prevent form from submitting
        console.log(data);
        $.ajax({
          type: "POST",
          async: true,
          url: test.php,
          data: $(this).serializeArray(),
          success: function (data) {
            console.log(data);
          }
         });
        });
     });
    </script>
  </body>
</html>

Hope this will help you.希望这会帮助你。

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

相关问题 我试图使用Ajax从数据库中检索数据,但无法正常工作 - I tried to retrieve data from database using Ajax but its not working 如何从数据库检索数据而不使用Ajax刷新页面 - how to retrieve data from database without refreshing page using ajax 使用Ajax从数据库检索数据 - Retrieve data from database using ajax 我如何将猫鼬查询的结果保存到变量 - How can i save results from mongoose query to a variable 我如何使用 axios 检索特定数据。现在它正在返回数据库中的所有数据 - How can i retrieve specific data using axios.Right now it is returning all the data from database 如何使用asp.net从数据库中检索数据,然后将该数据提供给javascript数组? - How can I retrieve data from a database using asp.net and then feed that data into a javascript array? 从数据库中检索数据并将其保存在变量中以进行一些计算并显示它 - Retrieve data from database and save it in a variable to do some calculation and diplay it 如何使用AJAX将DropDown保存到数据库中 - How can I save a DropDown into a Database with AJAX 如何从Firebase实时数据库检索数据? - How can I retrieve data from firebase realtime database? 如何从我的 firebase 数据库中检索数据? - How can I retrieve data from my firebase database?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM