如果我单击一个链接,它应该从与该链接对应的数据库加载数据并将数据显示到 div 中,但是当我单击时,什么也没有发生。基于我最初的问题有很多评论,我决定重新开始:Using a href onclick to update div without reloading page?
我的代码:
显示链接和数据的页面:
<a href="#" class="query-link" data-id="1" >text</a><br>
<a href="#" class="query-link" data-id="2" >text 2</a>
JavaScript 文件:
jQuery(document).ready(function() {
jQuery('a.query-link').on('click', function(e){
//Prevent the link from working as an anchor tag
e.preventDefault();
//Declare 'this' outside of AJAX because of asynchronous nature of call
that = jQuery(this);
//Make AJAX call to the PHP file/database query
jQuery.ajax({
url:'http://dirtypoliticsph.com/chart-submission/templatecode.php',
type:'POST',
data:{id:jQuery(this).data('id')},
success:function(data){
jQuery('#myStyle').append(data);
}
});
});
});
templatecode.php(调用数据库的文件):
if(isset($_GET['id']))
{
$results = $mysqli->query("SELECT * FROM PresidentialCandidate WHERE ID=".$_GET['id']);
if( $results->num_rows > 0 )
{
$row = mysqli_fetch_array($results,MYSQLI_ASSOC);
//Instead of just echoing out the ID, you need to build the result/data that you want in the div right here. The success function of the AJAX call will append whatever you echo out here
echo $row['id'];
}
}
最佳答案
尝试:
data:{id:jQuery(this).attr('data-id')},
您需要获取元素的“data-id”属性:
<a href="#" class="query-link" data-id="1" >text</a><br>
关于javascript - 链接未使用 ajax/jquery 从数据库加载数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34324115/