AJAX搜索和JSON响应

时间:2014-05-07 10:37:02

标签: php jquery ajax json

我试图用jQuery和PHP做一些简单的AJAX搜索。但是,我似乎无法使用正确的搜索字符串。我想按标题搜索,如果标题没有看到设置,只需在点击搜索时显示所有结果。此外,我想将结果显示为漂亮的HTML,而不是返回类似JSON的代码。像这样的东西:

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

SQL设置:

表名:书籍 表字段: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 个答案:

答案 0 :(得分:2)

您已在ajax中提及该方法,并尝试使用$title = $_GET["title"];

尝试使用

$title = $_POST["title"];

答案 1 :(得分:1)

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

答案 2 :(得分:1)

如果它是关于从JSON格式化HTML格式的输出,那么在你的jQuery代码中,你需要为数组中的每个json对象解析json并重复循环,并动态地将HTML添加到你的页面。

if(searchTitle) {
    $.ajax({
        type: "POST",
        url: "getBooks.php",
        data: data,
        success: function(res)
        {
            var my_table="<table>";
            $.each(res, function(i, obj){
                my_table+="<tr> <td> "+obj.clumn_name+" </td> <td> "+obj.clumn_name2+" </td> </tr> ";
            });
            my_table+"</table>";
            $("#search_results").html(my_table);
        }
    }); 
}