Ajax搜索将无法运行

I've upload my script to Fiddle and can be find here: http://jsfiddle.net/XdPk5/1/

I just can't seem to get it running, I'm trying to add errors, such as row count = 0 and if empty post has been sent

javascript:

        $(document).ready(function(){
            $(".search").click(function(){
                $.post(
                    "search.php", 
                    { keywords: $(".keywords").val() }, 
                      function(data) {
                        $("div#search").empty();
                        obj = JSON.parse(data);
                        $("div#search").append(obj.id + " " + obj.title);
                      },
                    "json"
                );
            });
        });

php:

<?php
$db = new PDO('mysql:host=localhost;dbname=db','root','');

$keywords = (isset($_POST['keywords']) === true) ? $_POST['keywords'] : '';
if (empty($keywords) === true) {
    echo json_encode( "error" );

} else {
    $query = $db->prepare("SELECT `media`.`id`, `media`.`title` FROM `media` WHERE `media`.`title` LIKE :keywords");

    if ($query->rowCount() == 0) {
        echo 'empty';

    } else {
        $query->bindValue(':keywords', '%' . $keywords . '%', PDO::PARAM_STR);

        $arr = array();
        $query->execute();
        while( $row = $query->fetch(PDO::FETCH_ASSOC) ) {
            $arr[] = array( "id" => $row["id"], "title" => $row["title"]);
        }
        echo json_encode( $arr );
    }
}

?>

This is wrong:

$query = $db->prepare("SELECT `media`.`id`, `media`.`title` FROM `media` WHERE `media`.`title` LIKE :keywords");

if ($query->rowCount() == 0) {
    echo 'empty';

} else {
    $query->bindValue(':keywords', '%' . $keywords . '%', PDO::PARAM_STR);
  • There is no rowCount before you execute the query;
  • If there are multiple words entered, you would need to build your sql query adding the individual keyword and chaining them together using OR or AND.

Also, where you do echo 'empty'; you are not returning valid json.

In the javascript, you probably mean dataType: "json" instead of just "json" as that is not a valid option.