如何使用GET在div中包含数据库查询的输出

时间:2017-11-13 12:21:45

标签: javascript php html postgis pg-query

我的index.html包含以下代码

<html>
<head><title>Testing</title></head>
<body>
<script>
  var javascriptVariable = "abc";
  window.location.href = "test_selected.php?name=" + javascriptVariable;
</script>
</body>
</html>

和包含代码的test_selected文件

<?php

$host = 'localhost';
$port = '5432';
$database = 'postgis';
$user = 'postgres';
$password = 'postgres';
$reg_name=$_GET['name'];

$connectString = 'host=' . $host . ' port=' . $port . ' dbname=' . $database . 
    ' user=' . $user . ' password=' . $password;


$link = pg_connect ($connectString);
if (!$link)
{
    die('Error: Could not connect: ' . pg_last_error());
}
$query="select * from table where name='{$reg_name}'";
$result = pg_query($query);

$i = 0;
echo '<html><body><table border="1"><tr>';
while ($i < pg_num_fields($result))
{
    $fieldName = pg_field_name($result, $i);
    echo '<td>' . $fieldName . '</td>';
    $i = $i + 1;
}
echo '</tr>';
$i = 0;

while ($row = pg_fetch_row($result)) 
{
    echo '<tr>';
    $count = count($row);
    $y = 0;
    while ($y < $count)
    {
        $c_row = current($row);
        echo '<td>' . $c_row . '</td>';
        next($row);
        $y = $y + 1;
    }
    echo '</tr>';
    $i = $i + 1;
}
pg_free_result($result);

echo '</table></body></html>';
?>

输出显示在新页面中,因为我使用了windows.location。是否可以在div中显示同一页面中的输出而不是另一个新页面。

1 个答案:

答案 0 :(得分:0)

在页面中包含jquery。并替换

window.location.href = "test_selected.php?name=" + javascriptVariable;

 $.ajax({
    type:'GET'
  url: "test_selected.php?name=" + javascriptVariable,
  success: function(result){
        $("#div_id").html(result);
},error:(error){
    console.log(error);
});

将div_id替换为您要加载的div的id。