首页 > 解决方案 > 单击按钮使用 AJAX 更新 PHP 中的数据库。我应该在数据选项卡中输入什么?

问题描述

这就是我的 PHP 文件的样子,我想点击一个按钮来运行它

<?php
 
        include("connection.php");
    include("formulaYT.php");
        
        $query = "UPDATE `songs` SET `views` = '".mysqli_real_escape_string($link, $_POST['content'])."' WHERE link = '".currentViews($soHigh)."'";
        
        mysqli_query($link, $query);
        
  
?>

以下是我的ajax代码。我应该在 ajax 'data:' 中放入什么。


<body>

    <button class="buttonTest">
      Test
    </button>

</body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>

    <script>

$(".buttonTest").click(function()
{
    
$.ajax({
  method: "POST",
  url: "updatedatabase.php",
  data: { content: $(".buttonTest").val() }
});

});
    </script>

我曾尝试在其他论坛上找到它,但根本找不到任何东西

标签: phpmysqlsqlajax

解决方案


数据”选项是您使用$ _POST函数发送到 php 脚本的内容。如果您没有要发送的内容(如您的情况),请不要使用“数据”选项

尝试这个:

文件.html

<button type="button">TEST</button>
<p></p>
<script type="text/javascript">
$(document).ready(function(){
    $("button").click(function(){ //the ajax starts only when the button 
                                  //identified by "type = button" is clicked

        $.ajax({
            type: 'POST',                 //type post (like php function $_POST)
            url: 'updatedatabase.php',       //your file
            success: function(data) {   //what to do when the php script it's done
                alert(data);
                $("p").text(data);       //inside the <p></p> it will print
                                         // the echo, in this case "done!"

               }
           });
      });
   });
   </script>

注意力!因为数据库查询不安全,你可以像现在这样进行sql注入攻击。我建议你纠正他们!

更新数据库.php

  <?php

  include("connection.php");
  include("formulaYT.php");
    
  $query = "UPDATE `songs` SET `views` = 
  '".mysqli_real_escape_string($link, $_POST['content'])."' WHERE link = 
  '".currentViews($soHigh)."'";
    
    mysqli_query($link, $query);
    
    echo "done!"   //all it's done

   ?>

推荐阅读