繁体   English   中英

我如何异步显示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查询的$ results,然后使用jquery.html(results)显示它们。 如何从JS页面访问php变量$ results?

没有很多代码。 这是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不太了解,但是看来您应该echo php的结果

$.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

   });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM