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


link not loading data from database using ajax/jquery

如果我点击一个链接,它应该从与该链接对应的数据库中加载数据,并将数据显示到div中,但当我点击时,什么都没有发生。基于我最初有很多评论的问题,我决定重新开始:使用href onclick更新div而不重新加载页面?

我的代码:

显示链接和数据的页面:

    <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>

您说过要从对应于该链接的数据库中加载数据,但我没有看到任何选择器将锚点标记作为服务器的响应。在jQuery('#myStyle').append(data);之后添加以下内容:

 jQuery('.query-link').append(data); 

并在templatecode中使用$_POST。顺便说一句,因为这些锚点使用相同的类名,所以它们都会受到影响。