【问题标题】:Do something with returned Ajax data from multiple SQL queries对从多个 SQL 查询返回的 Ajax 数据执行某些操作
【发布时间】:2021-01-07 14:22:15
【问题描述】:

如果我使用以下方法使用 MySQL 数据填充列表:

HTML

<ul id="first_column"></ul>
<br>
<ul id="second_column"></ul>

JQUERY/AJAX

$(document).ready(function() { 
  $.ajax({
    url: "filename.php",
    success: 
    function(data){            
        $("#first_column").html(data);
    }
  })
})

PHP

$conn = OpenCon();

$sql = "SELECT first_column FROM table";

$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){

    while ($row = mysqli_fetch_assoc($result)) {        
        echo '<li>' .$row['first']. '</li>';
    }
}

如何将第二个 SQL 查询 (SELECT second_column FROM table) 添加到 PHP 并从返回的 AJAX 数据中将其输出到 &lt;ul id="second_column"&gt;&lt;/ul&gt;?我想我必须使用数组和 json,但我很难弄清楚。

【问题讨论】:

    标签: php jquery arrays ajax


    【解决方案1】:

    更改您的 PHP 以回显 json 编码的字符串。

    $conn = OpenCon();
    
    $first_column = '';
    $second_column = '';
    
    $result = mysqli_query($conn, "SELECT first_column FROM table");
    if(mysqli_num_rows($result) > 0){
        while ($row = mysqli_fetch_assoc($result)) {  
    
            //append to `$first_column` instead of echoing directly      
            $first_column .= '<li>' .$row['first']. '</li>';
        }
    }
    
    //generate `$second_column` the same way as `$first_column`
    $result = mysqli_query($conn, "SELECT second_column FROM table");
    if(mysqli_num_rows($result) > 0){
        while ($row = mysqli_fetch_assoc($result)) {  
    
            //append to `$second_column`
            $first_column .= '<li>' .$row['second']. '</li>';
        }
    }
    
    //send both `$first_column` and `$second_column` at the same time
    echo json_encode(['first_column' => $first_column, 'second_column' => $second_column]);
    

    然后,在您的 ajax 中,您可以选择您想要的任何列。

    $(document).ready(function () {
        $.ajax({
            url: "filename.php",
            dataType: "json",
            success: function (data) {
                $("#first_column").html(data.first_column);
                $("#second_column").html(data.second_column);
            }
        })
    });
    

    或者,您可以进行单独的 Ajax 调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-11
      相关资源
      最近更新 更多