dqbn76906 2014-05-07 10:37
浏览 96
已采纳

AJAX搜索和JSON响应

I'm trying to do some simple AJAX searching with jQuery and PHP. However I can't seem to get the proper search string to work. I want to search by title, and if the title hasn't seen set, just display all results when clicking search. Also I would like to show the results as beautiful HTML and not returned back in JSON-like-code. Somthing like:

    $book["title"]
    $book["author"]
    $book["description"]

SQL Set-up:

Table Name: books Table Fields: id, title, author, description

HTML:

    <div id="search">
        <form action="#">
            <p><label for="title">Book Title:</label> <input type="text" id="search_title" name="search_title"></p>
            <p><input type="submit" id="search_submit" name="search_submit" value="Search!"></p>
            <p><em><small>For example A Game of Thrones or The Lord of the Rings</small></em></p>
            <hr>
        </form>
    </div>
    <div id="search_results">

    </div>
    <script>
        $(document).ready(function() {
            $("#search_submit").on("click", function() {
                var searchTitle = $("#search_title").val(),
                    data = 'title=' + searchTitle;

                if(searchTitle) {
                    $.ajax({
                        type: "POST",
                        url: "getBooks.php",
                        data: data,
                        success: function(res)
                        {
                            $("#search_results").html(res);
                        }
                    });    
                }
                return false;
            });
        });
    </script>

PHP:

if(isset($_GET["title"])) {
    $title = $_GET["title"];
}

if(isset($title) && !empty($title)) {
    $pdo_title = "WHERE title LIKE '%" . $title . "%'";
} else {
    $pdo_title = "";
}

$pdo_books = "books";

$pdo = new PDO("mysql:dbname=removed;host=removed","removed","removed");
$statement = $pdo->prepare("SELECT * FROM $pdo_books $pdo_title");
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo $json;
  • 写回答

3条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 如何关闭soui dummy wdn 进程
      • ¥20 含有jar文件的文件夹用tar -zcvf 命令压缩后要怎么还原回去?
      • ¥15 天宝TBC软件出现报错怎么解决
      • ¥15 micropython 从1开始切片报错
      • ¥15 请问该怎么做才能将文字说明和二维码一起作为png图片一起下载
      • ¥15 r语言 混频数据回归 midas_r
      • ¥15 人脸识recogizer.predict返回值id报错,KeyError,详情如下
      • ¥15 geowebcache部署失败
      • ¥20 关于adaboost+haar特征实现人脸检测过程的一些细节问题
      • ¥15 csv文件增加一列 为csv文件的名字