gpt4 book ai didi

javascript - 如何通过 PHP post 请求获取 JavaScript 变量?

转载 作者:行者123 更新时间:2023-12-03 07:05:10 26 4
gpt4 key购买 nike

我正在通过 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>

非常感谢您的帮助。

最佳答案

在您的 post.php 中,您可以简单地回显数组,jQuery 会自动将其转换为 array 作为响应

// post.php
<?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]);
}

echo json_encode($cols);
?>

// Somewhere in your js
$.post(
"post.php",
{
region: region,
district: district
},
function(data) {
console.log(data[0]);
}
);

关于javascript - 如何通过 PHP post 请求获取 JavaScript 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60537650/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com