使用href onclick更新div而不重新加载页面? [英] Using a href onclick to update div without reloading page?

查看:117
本文介绍了使用href onclick更新div而不重新加载页面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用这个现有的问题来帮助我: HTML - 更新页面内容,无需刷新重新加载页面。



template-comparison.php文件从header.php中提取代码代码,但实际的提取代码未显示。否则,模板页面将没有标题。 templatecode.php文件是用于获取和显示数据库数据的代码。



我的代码:



template-comparison.php

 < a href =#onClick =prescand(' 1')>链接文字< / a> 
< a href =#onClick =prescand('2')>链接文字2< / a>
< div id ='myStyle'>
< / div>

templatecode.php

 <?php 
$ servername =localhost;
$ username =出于安全目的隐藏;
$ password =出于安全目的隐藏;
$ dbname =出于安全目的而隐藏;

//创建连接
$ conn = new mysqli($ servername,$ username,$ password,$ dbname);
//检查连接
if($ conn-> connect_error){
die(Connection failed:。$ conn-> connect_error);
}

$ ID = $ _GET ['ID'];
$ results = mysql_query(SELECT * FROM PresidentialCandidate WHERE ID ='$ ID');
if(mysql_num_rows($ results)> 0)
{
$ row = mysql_fetch_array($ results);
echo $ row ['ID'];
}
?>

header.php

 < script type =text / javascript> 
函数prescand(ID){
$('#myStyle')。load('templatecode.php?id ='+ ID);
}
< / script>

会发生什么:

我点击链接。什么都没发生。它就像一个锚点,将我推到页面的顶部。



任何想法?我想要的是在链接中点击链接的数据(例如:ID 1 ...链接文本)的全部显示在div中。如果我点击ID 2(链接文本2),就会显示该ID的数据。

解决方案

我有更长的答案下面,但你可以做的一件事,以防止它像一个锚标签行事就是调用event.preventDefault();在你的函数之前的onclick():

template-comparison.php

 < a href =#onClick =event.preventDefault(); prescand('1'); >链接文字< / a> 
< a href =#onClick =event.preventDefault(); prescand('2')>链接文本2< / a>
< div id =myStyle>
< / div>






使用这样的AJAX:



template-comparison.php

 < a href =#class =query-linkdata-id =1>链接文字< / a> 
< a href =#class =query-linkdata-id =2> link text 2< / a>
< div id =myStyle>
< / div>

header.php



(pre> jQuery(document).ready(function(){
jQuery('a.query-link')。on('click',function(e){
//防止链接作为锚点标记
e.preventDefault();

//对PHP文件/数据库查询进行AJAX调用
jQuery .ajax({
url:'{PATH TO FILE} /templatecode.php',
type:'POST',
data:{id:jQuery(this).data('id ')},
success:function(data){
jQuery('#myStyle')。append(data);
}
});
}) ;
});

templatecode.php

 <?php 
$ servername =localhost;
$ username =出于安全目的隐藏;
$ password =出于安全目的隐藏;
$ dbname =出于安全目的而隐藏;

//创建连接
$ mysqli = new mysqli($ servername,$ username,$ password,$ dbname);
//检查连接
if($ mysqli-> connect_error){
die(Connection failed:。$ mysqli-> connect_error);
}

$ ID = $ _POST ['ID'];
$ results = $ mysqli-> query(SELECT * FROM PresidentialCandidate WHERE ID ='$ ID');
if($ results-> num_rows> 0)
{
$ row = mysqli_fetch_array($ results,MYSQLI_ASSOC);

//不要仅仅回显ID,你需要在这里创建你想要的结果/数据。 AJAX调用的成功函数将追加你在这里回显的任何内容
echo $ row ['ID'];
}
?>

顺便说一句,我更新了您的PHP代码以正确使用MySQLI,而不是将MySQL与MySQLi混合。



看到您的网站(WordPress)后,您不会直接在header.php中加载它。其中一个问题是jQuery在该脚本之后被加载,因此它在加载时没有使用jQuery变量。您可以尝试将其放入footer.php文件中,但正确的方法是将其放入外部脚本中,然后在您的functions.php文件中使用wp_enqueue_script加载它。


I used this existing question to help me out: HTML - Change\Update page contents without refreshing\reloading the page

The template-comparison.php file fetches the code from the header.php code but the actual "fetch code" isn't shown. Otherwise, the template page would have no header. The templatecode.php file is the code used to fetch and display the database data.

My code:

template-comparison.php

    <a href="#" onClick="prescand('1')" >link text</a>
    <a href="#" onClick="prescand('2')" >link text 2</a>
    <div id='myStyle'>
    </div>

templatecode.php

    <?php
    $servername = "localhost";
    $username = "hidden for security purposes";
    $password = "hidden for security purposes";
    $dbname = "hidden for security purposes";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    } 

      $ID = $_GET['ID'];
      $results = mysql_query("SELECT * FROM PresidentialCandidate WHERE  ID='$ID'");   
      if( mysql_num_rows($results) > 0 )
      {
       $row = mysql_fetch_array( $results );
       echo $row['ID'];
      }
    ?>

header.php

   <script type="text/javascript">
    function prescand(ID) {
      $('#myStyle').load('templatecode.php?id=' + ID);
    }
    </script>

What happens:

I click the link. Nothing happens. It just acts like an anchor that pushes me to the top of the page.

Any ideas? What I want is to have ALL of the data for the link clicked (eg: ID 1...link text) to be displayed in the div. If I click, ID 2 (link text 2), the data for that ID is shown.

解决方案

I have a longer answer below but one thing you can do to prevent it from acting like an anchor tag is to just call event.preventDefault(); on the onclick() before your function:

template-comparison.php

<a href="#" onClick="event.preventDefault();prescand('1');" >link text</a>
<a href="#" onClick="event.preventDefault();prescand('2')" >link text 2</a>
<div id="myStyle">
</div>


Use AJAX like this:

template-comparison.php

<a href="#" class="query-link" data-id="1">link text</a>
<a href="#" class="query-link" data-id="2">link text 2</a>
<div id="myStyle">
</div>

header.php

jQuery(document).ready(function(){
    jQuery('a.query-link').on('click', function(e){    
        //Prevent the link from working as an anchor tag
        e.preventDefault();

        //Make AJAX call to the PHP file/database query
        jQuery.ajax({
            url:'{PATH TO FILE}/templatecode.php',
            type:'POST',
            data:{id:jQuery(this).data('id')},
            success:function(data){
                jQuery('#myStyle').append(data);
            }
        });
    });
});

templatecode.php

<?php
$servername = "localhost";
$username = "hidden for security purposes";
$password = "hidden for security purposes";
$dbname = "hidden for security purposes";

// Create connection
$mysqli = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
} 

  $ID = $_POST['ID'];
  $results = $mysqli->query("SELECT * FROM PresidentialCandidate WHERE  ID='$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'];
  }
?>

BTW, I updated your PHP code to use MySQLI properly instead mixing MySQL with MySQLi.

After seeing your site (WordPress), you're not going to want to load this in the header.php directly. One of the issues is that jQuery is being loaded AFTER this script so it doesn't have the jQuery variable to use yet when it loads. You can try by putting it in the footer.php file but the 'right' way to do it is to put it in an external script and then load it using wp_enqueue_script in your functions.php file.

这篇关于使用href onclick更新div而不重新加载页面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆