如何异步显示SQL查询的结果(使用ajax)


How I do aysnchronously display the results of an SQL query (with ajax)?

我仔细浏览了这个网站,发现了类似的问题,但不明白答案。也许我需要更熟悉AJAX,但这是我的问题:

我有一个PHP页面(mymdb.php),其中用户提交信息(一个姓和名)。我有一个获取mysql_query (_results.php)结果的页面。最后,我有一个JS页面(bacon.js),这意味着异步显示查询的结果(通过淡出一个div,并向下滑动它上面的结果)。

所以我认为我需要以某种方式访问SQL查询的$结果,然后使用jquery.html(结果)显示它们。我如何从JS页面访问php变量$结果?

没有很多代码。以下是用户提交信息的mymdb.php页面的相关代码:

<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <script src='//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js'></script>
    <script src="bacon.js" type="text/javascript"></script>
</head>
<body>
    <div class="main">
        <form method="post" action="mymdb.php" id="search_form">
            <fieldset id="search_box">
                Actor's first last name:
                <input name="first_name" type="text" size="12" id="fname" /> 
                <input name="last_name" type="text" size="12" id="lname" /> 
                <button type="submit" name="submitButton" id="submitButton">go</button>
            </fieldset>
        </form>
        <div id="everythingElse">
            <h1>The One Degree of Kevin Bacon</h1>
            <p>
                Type in an actor's name to see if he/she was ever in a movie with Kevin Bacon!
            </p>
            <p id="result_paragraph">
            </p>
            <div id="kevinBaconImg"><img src="http://www.images22.com/pics/04/kevin-bacon-blue-eyes.jpg" alt="Kevin Bacon"/></div>
        </div>
    </div>
</body>

下面是SQL查询的_results.php页面:

<?php
    mysql_connect("localhost", "username", "password");
    mysql_select_db("imdb_small");
    //get all movies the actor is in
    $results1 = mysql_query("SELECT name, year 
        FROM movies m 
            JOIN roles r ON m.id = r.movie_id 
        JOIN actors a ON a.id = r.actor_id 
        WHERE a.first_name = $('#fname').val() AND a.last_name = $('#lname').val();"
    );
?>
下面是JS代码:
$(document).ready(function() {
    $('#submitButton').click(function(e) {
        e.preventDefault();
        $.post('mymdb.php', $('#search_form').serialize(), function() {
            $('#result_paragraph').html('<?= $results1 ?>').slideDown(); //this should dislay the results from the query
            $('#kevinBaconImg').fadeOut(); //this image fades out once the user submits the first and last names of the actor
        });
    });
});   

使用回调函数中获得的数据

我不太了解php,但似乎你应该从你的php

echo结果
$.post('mymdb.php', $('#search_form').serialize(), function(result) {
            $('#result_paragraph').html(result).slideDown(); //this should dislay the results from the query
            $('#kevinBaconImg').fadeOut(); //this image fades out once the user submits the first and last names of the actor
   });