簡體   English   中英

如何在不使用php和Ajax重新加載的情況下從同一頁面上的mysql獲取數據

[英]How to fetch data from mysql on the same page without reloading using php and ajax

我有這段代碼,假設是要從mysql提取數據,這里有用戶列表,因此,如果您單擊一個用戶,它將顯示該用戶的詳細信息,但是每當我單擊例如用戶3或4時,它只會獲取用戶1。我需要幫助這是

fetch.php

<?php
       $connection = mysql_connect('localhost', 'root', '');
       $db = mysql_select_db('temp', $connection);
       $x = $_POST['id'];
       $safex = mysql_real_escape_string($x);
   $query = mysql_query("select * from class where id=$safex",  $connection);

   $result = "";

      $result .= "<div id='display'>";
      $result .="<table border=\"1\">";
      $result .="<tr><th>Name</th><th>Password(encrypted)</th></tr>";
        while($row = mysql_fetch_assoc($query)){
$result .= "<tr><td> {$row['name']}</td>"."<td> {$row['password']}</td></tr></p>";
}
$result .="</table>";

$result .= "</div>";
echo $result;

?>

這是

index.php

    <?php
$connection = mysql_connect('localhost', 'root', '');
$db = mysql_select_db('temp', $connection);
?>
<html>
<head>
<title>Fetch record using jQuery</title>
<style type="text/css">
#display {
margin : 225px;
}
</style>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$('document').ready(function(){

$('a').click(function(){
var temp = $('a').attr('myval');
$.post('fetch.php', {id:temp}, function(data){
$('#display').html(data);
});
});
});
</script>
</head>
<body>
<?php
$query = mysql_query("select * from class order by id desc LIMIT 2", $connection);
echo "<ul>";
while($row = mysql_fetch_assoc($query)){
echo "<li><a href=\"javascript:return(0)\" myval=\"{$row['id']}\"><h3>{$row['name']}</h3></a></li>";

}

echo "</ul>";

?>
<div id="display"></div>
</body>
</html>
<?php
mysql_close($connection);
?>

使用mysql_fetch_array()mysql_fetch_assoc()

while($row = mysql_fetch_array($query)){
$result .= "<tr><td> {$row['name']}</td>"."<td> {$row['password']}</td></tr></p>";
}

問題不在數據庫中。 您的代碼的問題是語句

var temp = $('a').attr('myval');

使用以下代碼:

$('a').click(function(this){
    var temp = $(this).attr('myval');
    $.post('fetch.php', {id:temp}, function(data){
         $('#display').html(data);
    });
 });

變量“ temp”始終會獲取錨標記的第一個ID。 其余代碼都可以。

謝謝'Honza Haering',它現在正在工作,問題是我使用了var temp = $('a')。attr('myval'),但正確的是這個var temp = $(this).attr('myval')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM