我通过这个网站非常努力地寻找并发现了类似的问题,但不明白答案。也许我需要更加熟悉 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
});
});
});