如何在提交表单时使用其他SQL查询重新加载div?

时间:2016-07-18 10:44:25

标签: php jquery html ajax post

我有一个HTML form(用作搜索框),当我提交这个form时,我想要重新加载带有研究结果的div。

例如:

在我的div中,我有这样的查询:

SELECT * FROM users; 

我会显示所有idsnames

当我提交表单时,我想要这样的查询:

SELECT * FROM users WHERE name=$_POST['search']; 

并在我的div用户中显示与研究匹配而不重新加载所有页面但只是这个div。

我该怎么办呢?

2 个答案:

答案 0 :(得分:0)

您可以使用jQuery load功能。我给你写了一个简单的使用这个功能,希望你是解决问题的指路明灯:

当然,您需要更改指向工作环境的链接。

<强>的index.php

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

if (isset($_GET["search"])) {
    $sth = $pdo->prepare("SELECT name FROM users WHERE name = '{$_GET["search"]}'");
    $sth->execute();
    $result = $sth->fetchAll(PDO::FETCH_ASSOC);
    $response = array();
    foreach ($result as $responseIndex => $responseValue) {
        $response[] = $responseValue["name"];
    }
    die(implode(",", $response));
}
?>

<form method="GET" action="http://localhost/test/index.php">
    <input name="search" type="text" id="search-value" />
    <input type="submit" id="search-button"/>
</form>

<div id="container"></div>

<script>
    $("#search-button").on("click", function (e) {
        e.preventDefault();
        $("#container").load("http://localhost/test/index.php?search=" + $("#search-value").val());
    });
</script>

答案 1 :(得分:0)

的index.php

<form method="GET" action="http://localhost/test/index.php">
    <input name="search" type="text" id="search-value" />
    <input type="button" id="search-button"/>
<div id="container"></div>
</form>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
 $(document).ready(function () {
          $('#search-button').click(function () {
                                        var searchval = $("#search-value").val();
                                        $.post('search.php', {'search_val': searchval, 'action': 'search'}, function (data) {
                                            $("#container").html(data);
                                        });


          });
    });

</script>

的search.php

<?php
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

if (isset($_POST["search"])) {

$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $sth = $pdo->prepare("SELECT name FROM users WHERE name = '".$_POST['search_val']."'");
    $sth->execute();
    $result = $sth->fetchAll(PDO::FETCH_ASSOC);
    $response = array();
    foreach ($result as $responseIndex => $responseValue) {
        $response[] = $responseValue["name"];
    }
    die(implode(",", $response));
}
?>