提交搜索查询并显示结果,无需刷新页面

时间:2016-03-19 12:16:26

标签: php jquery

我有一个输入框,提交后,它会检查数据库中的结果,刷新页面然后显示结果。

有没有办法在显示结果时阻止页面刷新?

这是我的剧本:

    <form method="post">
    <input type="text" name="search">
    <input type="submit" name="submit">
    </form>
    <?php echo $results; ?>

<?php

$con = mysqli_connect("localhost","dbuser","dbpass","dbname");

if(isset($_POST['submit'])) {

$term = mysqli_real_escape_string($con, $_REQUEST['search']);

$sql = "SELECT * FROM `users` WHERE username LIKE '%".$term."%'"; 
$r_query = mysqli_query($con, $sql); 

while ($row = mysqli_fetch_array($r_query)){ 
$results = $row['username'];  
}
}
?>

3 个答案:

答案 0 :(得分:0)

让我们给那个表格一个id:

<form method="post" id="my-test">
<input type="text" name="search">
<input type="submit" name="submit">
</form>

让我们为它编写一个处理程序:

function submitMyTest(e) {
    //We do not want to reload the page
    e.preventDefault();
    //gather inputs
    var inputs = $(this).find("input[name],textarea[name]");
    var data = {};
    inputs.each(function() {
        data[$(this).attr("name")] = $(this).val();
    });
    $.ajax({
        url: 'yoururl/yourpage.php',
        medhot: 'POST'
        data: data,
        success: function(response) {
            //handle response
        }
    })
}

在某个地方,也许在加载事件中将此附加到标记的提交中,如下所示:

$(function() {
    $("#my-test").submit(submitMyTest);
});

答案 1 :(得分:0)

尝试html5 pushstate() popstate() 功能。我希望它能奏效。

答案 2 :(得分:0)

1)id中创建一个target作为<form>。在id中使用此<script></script>

2)创建一个<div></div>,其类名为showResult。所有结果都将来临&amp;只参与此<div>

<form id="target">
    <input type="text" name="search" id="search_name">
    <input type="submit" name="submit">
</form>

<div class="showResult"></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $( "#target").submit(function( event ) {  
        event.preventDefault();
        var search_name=$('#search_name').val();
        $.ajax({url:"AjaxPage.php?search_name="+search_name,cache:false,success:function(result){
          $('.showResult').html(result);
        }});
    });
});
</script>

AjaxPage.php (创建新页面&amp;确保此页面名称与<script></script>中使用的页面名称相同。两者都相关。)

<?php
$con = mysqli_connect("localhost","dbuser","dbpass","dbname");

$term = mysqli_real_escape_string($con, $_GET['search_name']);

$sql = "SELECT * FROM `users` WHERE username LIKE '%".$term."%'"; 
$r_query = mysqli_query($con, $sql); 

while ($row = mysqli_fetch_array($r_query)){ 
    echo $row['username'];  
}
?>