このサイトをよく見て、同様の質問を見つけましたが、答えがわかりませんでした。おそらく私は AJAX にもっと慣れる必要がありますが、ここに私の問題があります:
ユーザーが情報 (姓名) を送信する PHP ページ (mymdb.php) があります。mysql_query (_results.php) の結果を取得するページがあります。最後に、JS ページ (bacon.js) があります。これは、クエリの結果を非同期的に表示することを目的としています (1 つの 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
});
});
});