duanqiu2064 2013-05-15 19:10
浏览 59
已采纳

jQuery Ajax PHP搜索栏只能运行一次

I've build a small search engine for my websites blog articles, I'm submitting the form with Ajax and then returning the results and replacing the old content with the new search results the problem is that if I search once it works but if I search again it just displays the results from the first search. Any help would be great thanks in advance!

HTML

<form action="handlers/handler-search.php" class="align-right" method="post">
    <input type="text" name="term"  placeholder="Search app reviews...">
    <input type="submit" value="Go">
</form>

jQuery Ajax

    $('form').submit(function (event) {

    event.preventDefault();

    $(".content").fadeOut(750);

    $.ajax({
        type: "POST",
        url : $('form').attr('action'),
        dataType: "json",
        data: $("form").serialize()
    }).done(function(data) {

        var string = "";

        $.each(data, function(i,item) {

         string += "<section class='widget six'> \
         <a href='index.php?art_id="+item.art_id+"'> \
         <div class='content'> \
         <h1>"+item.art_title+"</h1> \
         </div> \
         </a> \
         </section>";

        });

        $('.results').replaceWith(string);
        $(".content").fadeIn(750);
    });

   return false;
});

PHP / SQL

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

$statement_search = $db->prepare("SELECT * FROM app_articles WHERE art_title LIKE :term");

$statement_search->setFetchMode(PDO::FETCH_ASSOC);

$statement_search->execute(array(':term' => '%'.$_POST['term'].'%'));   

$data = $statement_search->fetchAll();

echo json_encode($data);
}
  • 写回答

1条回答

  • dshun123456 2013-05-15 19:20
    关注

    You are removing the results element, you should instead replace it's contents.

    $('.results').html(string);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条