如何通过 PHP 发布请求获取 JavaScript 变量?

我通过 jquery ajax发布PHP文件( )。post.php我想以 javascript 变量的形式从中获取数据。我成功地在我的控制台中获取了数据。但我不知道如何使用这个变量。你可以在下面看到我的代码。


$.post(

    "post.php",

    {

      region: region,

      district: district

    },

    function(data) {

      console.log(data);

    }

  );

我的 post.php 页面看起来像这样


    @include('../../_partials/_dbConnect.php');

    $region = $_POST['region'];

    $district = $_POST['district'];

    $sql = "SELECT * FROM table1 WHERE name_rg= '".$region."'";

    $result = pg_query($db_connection, $sql);

        while ($row = pg_fetch_row($result)) {

            $cols = array($row[0],$row[1],$row[2],$row[3],$row[4],$row[5],$row[6],$row[7],$row[8],$row[9],$row[10],$row[11],$row[12],$row[13],$row[14],$row[15],$row[16],$row[17],$row[18],$row[19],$row[20],$row[21]);

        }

<script>

  var cols = [<?php echo '"'.implode('","', $cols).'"' ?>];

</script>

console.log(data)像这样的输出,


<script>

  var cols = ["94","32","361","0","118","159","0","243","702","1775","8","0","2","0","150","135","381","2","0","0","0","0"];

</script>

非常感谢您的帮助。


慕虎7371278
浏览 129回答 2
2回答

红颜莎娜

在您的post.php中,您可以简单地回显数组,jQuery 应该自动将其转换array为响应// post.php<?php&nbsp; &nbsp; @include('../../_partials/_dbConnect.php');&nbsp; &nbsp; $region = $_POST['region'];&nbsp; &nbsp; $district = $_POST['district'];&nbsp; &nbsp; $sql = "SELECT * FROM table1 WHERE name_rg= '".$region."'";&nbsp; &nbsp; $result = pg_query($db_connection, $sql);&nbsp; &nbsp; while ($row = pg_fetch_row($result)) {&nbsp; &nbsp; &nbsp; &nbsp; $cols = array($row[0],$row[1],$row[2],$row[3],$row[4],$row[5],$row[6],$row[7],$row[8],$row[9],$row[10],$row[11],$row[12],$row[13],$row[14],$row[15],$row[16],$row[17],$row[18],$row[19],$row[20],$row[21]);&nbsp; &nbsp; }&nbsp; &nbsp; echo json_encode($cols);?>// Somewhere in your js$.post(&nbsp; &nbsp; "post.php",&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; region: region,&nbsp; &nbsp; &nbsp; district: district&nbsp; &nbsp; },&nbsp; &nbsp; function(data) {&nbsp; &nbsp; &nbsp; console.log(data[0]);&nbsp; &nbsp; });

慕码人8056858

在 javascript 中使用 JSON.parse()$.post(&nbsp; &nbsp; "post.php",&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; region: region,&nbsp; &nbsp; &nbsp; district: district&nbsp; &nbsp; },&nbsp; &nbsp; function(data) {&nbsp; &nbsp; &nbsp; data=JSON.parse(data);&nbsp; &nbsp; });```And here you go, u can play with it as you needHappy learning!
打开App,查看更多内容
随时随地看视频慕课网APP