单击按钮时如何将变量从php for()传递给ajax?

时间:2020-09-01 10:24:46

标签: javascript php jquery ajax

当单击(.refresh)按钮时,如何将$ data_name传递给ajax,而ajax将在php脚本的body字段中通过for()获得? 我想传递用于从数据库中选择数据的变量。

2Scripts:
(1) html formated .php file>
ajax written in header field,
php for() written in body field
(2) SQL select script in php, added 
$dataname= $_POST['dataname']; 

在for()中,我从数据库中获取数据并显示数据表DATA A〜C。 单击每个数据的按钮时,我想从数据库中获取新数据。 我能够得到它,只需为Ajax写“ A”,但我想为许多表传递变量。 [在此处输入图片描述] [1] [1]:https://i.stack.imgur.com/zpJ7B.png

<head>
<script>
$(document).ready(function(){
  $('.refresh').click(function(){
    $.ajax({
        // 通信先ファイル名
        url: "select.php",
        type: "POST",
        data: ({"data_name": $data_name}),
        success: function(data) {
        //more code
        },
        error: function(data) {         
        //more code
        }
});
</script>
</head>
<body>
<?php
        //more code for(){  getting $data_name(A、B、C)here >
        echo <<<EOD
        <button class='refresh'>REFRESH DATA</button>
        <table class='show'></table>
EOD;
?>
</body>

2 个答案:

答案 0 :(得分:0)

您可以使用其他PHP返回JSON或相同的JSON。 因此,如果您要使用相同的脚本,则您基本上希望在PHP脚本获得POST时发送带有数据的JSON。 因此,您必须检查:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
     // The request comes from Javascript doing POST
     // Query Database and return a JSON with the field "data_name"
} else {
     // Render your form like now you're doing now, the request com from the browser loading the page
}

答案 1 :(得分:0)

//select.php
<?php 
 $data= $_POST["data_name"];

 echo  json_encode( $data);
?>
<script>
$(document).ready(function(){
  $('.refresh').click(function(){
    $.ajax({
        // 通信先ファイル名
        url: "select.php",
        type: "POST",
        data: ({"data_name": $data_name}),
        success: function(data) {
        
         // getting $data_name(A、B、C)here


        },
        error: function(data) {         
        //more code
        }
});
</script>