如果我点击链接,它应该从数据库中加载与该链接相对应的数据并将数据显示到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'];
}
}
答案 0 :(得分:0)
您说您想要从与该链接对应的数据库加载数据,但是我没有看到任何选择器将锚标记作为来自服务器的响应。在jQuery('#myStyle').append(data);
:
jQuery('.query-link').append(data);
并在templatecode
中使用 $ _ POST 。顺便说一下,因为这些锚使用相同的类名,所以它们都会受到影响。
答案 1 :(得分:0)
尝试:
data:{id:jQuery(this).attr('data-id')},
您需要获取元素的'data-id'属性:
<a href="#" class="query-link" data-id="1" >text</a><br>