javascript - 链接未使用 ajax/jquery 从数据库加载数据

标签 javascript php jquery ajax

如果我单击一个链接,它应该从与该链接对应的数据库加载数据并将数据显示到 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/

相关文章:

javascript - 如何在特定数字处停止 JavaScript 计数器

php - 如何搜索序列化存储的字符串

php - 如何从我的热门列表中排除某些名字

javascript - 使用 jquery 隐藏和显示覆盖模态

javascript - JSON 字段未定义 (Javascript)

javascript - Jquery 错误放置 with required from group

javascript - 如何在模态显示之前刷新 Bootstrap 模态刷新

php - 使用 PHP 显示结果时在搜索框中显示搜索条件

javascript - 遍历 div 内的输入

javascript - 任何用于创建水平月历(一个类轮)的 Jquery 插件?