如何使用Ajax显示和隐藏div?

时间:2015-01-31 16:03:32

标签: javascript php ajax

我知道我的问题似乎很容易解决(或者在google上找到解决方案),但我认为它比我在标题中写的更复杂......

我需要创建像facebook通知这样的东西:每隔X秒,通过Ajax启动查询以检查DB上的值是0还是1,如果它是0,则div出现!

这是我如何设法做到这一点

打印div的代码:

function stampa_new_friend_request() {

return "<script> 
    window.setInterval('controllaAmicizie()', 500); 
    </script>

    <div id='friend_request'> 
    </div>";}

JS函数

function setXMLHttpRequest(handler) {
    var xhr = null;

    if ( window.XMLHttpRequest ) {
        xhr = new XMLHttpRequest();
    }
    else if ( window.ActiveXObject ) {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xhr.onreadystatechange = handler;
    return xhr;
}

function handler() {
    if (myRequest.readyState == 4 && myRequest.status == 200) {
        riempi_friend_request(myRequest.responseText);}
}


function controllaAmicizie() {
    myRequest = setXMLHttpRequest(handler);
    myRequest.open('GET','friend_notification.php');
    myRequest.send(null);
}

function riempi_friend_request(richiesta) {
    var div = document.getElementById("friend_request");
    if (div.style.visibility == 'hidden') {
        div.style.visibility = 'visible';
        div.style.display = 'block';
    } 
    else {
        div.style.visibility = 'visible';
        div.style.display = 'block';
    }       

    div.innerHTML = "<p><a class='alert' href='friend_request.php'>" + richiesta + "</a></p>";
}

PHP页面friend_notification.php

<?php 

include("functions/layout_functions.php"); 
include("functions/db_functions.php");

$mysqli = connetti_db(); 
session_start();

$query = "SELECT * FROM amici WHERE id_ricevente =".$_SESSION['id']." AND      user_ricevente='".get_user()."' AND confirmed = '0'";
$result = $mysqli->query($query);

if (mysqli_num_rows ($result) > 0) echo "Hai ".mysqli_num_rows ($result)." nuove richieste di amicizia";

else if (mysqli_num_rows ($result) == 1) echo "Hai ".mysqli_num_rows  ($result)." nuova richiesta di amicizia";

disconnetti_db($mysqli);

?> 

一切都运行良好,但是当我刷新页面时,div需要半秒才能展示自己(因为setInterval()):当第一个显示div时时间(当查询查找结果时)我希望它保持可见,直到查询结果为0(并且每次刷新页面时不再“重新充值”)。

对不起我的baaaaaad英语,我希望你能理解我的问题!

谢谢!

3 个答案:

答案 0 :(得分:0)

调用该函数以在页面加载时立即显示DIV:

function stampa_new_friend_request() {

    return "<script> 
            window.onload = function() {
                window.setInterval(controllaAmicizie, 500); 
                controllaAmicizie;
            };
            </script>

            <div id='friend_request'> 
            </div>";
}

BTW,最好将函数传递给setInterval而不是字符串。

答案 1 :(得分:0)

&#13;
&#13;
function controllaAmicizie_fake() {
  myRequest = doPost();

}


function riempi_friend_request(richiesta) {
  var div = document.getElementById("friend_request");
  if (div.style.visibility == 'hidden') {
    div.style.visibility = 'visible';
    div.style.display = 'block';
  } else {
    div.style.visibility = 'visible';
    div.style.display = 'block';
  }

  div.innerHTML = "<p><a class='alert' href='friend_request.php'>" + richiesta + "</a></p>";
}

document.getElementById("friend_request").className = "hide";

//this fakes a call to the server
//I can't really do a server call in the code snippet
//This is a proof of concept. You should implement the idea of doPost into your own code inside the function handler.

function doPost() {
  var random = Math.floor(Math.random() * 2)

  if (random) {
      riempi_friend_request("New friends");
      document.getElementById("friend_request").className = null;
  }
  else {
     document.getElementById("friend_request").className = "hide";
  }
  document.getElementById("serverPoll").innerHTML += "Server Poll returns: " + (random ? true : false) + "<br />"; 
  
  window.setTimeout(controllaAmicizie_fake, 1000); //wait another second to do a new poll.
}
controllaAmicizie_fake();
&#13;
.hide {
  display: none !important;
}
&#13;
<div id="friend_request"></div>


<div id="serverPoll"></div>
&#13;
&#13;
&#13;

这段代码举例说明了我的意思。由于在脚本底部调用controllaAmicizie_fake();,它将直接在页面上执行。在您的代码中,这是controllaAmicizie()。然后启动HTTP请求。如果它返回,则创建一个新的超时,触发另一个服务器轮询。

与您的代码不同的是页面上存在朋友div。它是在页面加载时创建的,并且被代码隐藏起来。每次服务器返回true时,都会显示它。

答案 2 :(得分:0)

好的伙计们,我解决了这个问题......这有点棘手,但它确实有效!每次查询找到结果时,它都会设置一个类似&#34的会话变量;你有1个请求&#34; (如回声),当它找不到更多结果时,它会取消变量和回声&#34; 0&#34;。在显示div之前,js检查是否&#34; risposta&#34; (这是来自php的回声)是!= 0:是的,有新的请求,所以显示div;不,没有新的要求,保持潜水隐藏。

然后在html页面中我有2个脚本:第一个,如果设置了会话变量,则打印div用变量本身填充它(不用每次询问带有ajax的db);第二,如果未设置变量,则运行ajax以查找新请求(这解决了&#34;加载瞬间&#34;每次刷新时)。

然后我遇到了这个小问题:我在左边有这个通知&#34; 1请求&#34;和右边的页面,用表单接受请求。如果我接受,通知会对&#34; 1请求&#34;直到我刷新页面。我用#34解决了这个问题;如果(richiesta == 0)&#34;在js代码中:如果它是真的,它会强迫richiesta的价值为&#34;没有新的请求&#34;并将其打印在div中,替换旧的&#34; 1新请求&#34;从会话值!

这里是代码

用于打印和填充div的HTML代码

function stampa_new_friend_request(){// stampa il div se ci sono nuove richieste di amicizia

if(isset($_SESSION['request'])){
return "<div id='friend_request' class='show'><p><a class='alert' href='friend_request.php'>".$_SESSION['request']."</a></p></div>                  

<script>
window.onload = function() {
window.setInterval(controllaAmicizie, 2000); 
controllaAmicizie();
};
</script>";}

else return "<div id='friend_request' class='hide'></div>
    <script>
    window.onload = function() {
    window.setInterval(controllaAmicizie, 2000); 
    controllaAmicizie();
    };
    </script>";
}

JS代码(我只修正了这个功能)

function riempi_friend_request(richiesta) {

var div = document.getElementById("friend_request");

if(richiesta != 0){

  if (div.style.visibility == 'hidden') {
  div.style.visibility = 'visible';
  div.style.display = 'block';
} 
else {
  div.style.visibility = 'visible';
  div.style.display = 'block';
}   

 div.innerHTML = "<p><a class='alert' href='friend_request.php'>" +   richiesta + "</a></p>";   
}


else if (richiesta == 0) {

   richiesta = "Non hai nuove richieste di amicizia";
   div.innerHTML = "<p><a class='alert' href='friend_request.php'>" + richiesta + "</a></p>";

}

else return;

}

和PHP代码

<?php 

include("functions/layout_functions.php"); 
include("functions/db_functions.php");

$mysqli = connetti_db();
session_start();

$query = "SELECT * FROM amici WHERE id_ricevente =".$_SESSION['id']." AND      user_ricevente='".get_user()."' AND confirmed = '0'";
$result = $mysqli->query($query);

if (mysqli_num_rows ($result) == 1) {

    echo "Hai ".mysqli_num_rows ($result)." nuova richiesta di amicizia";
    $_SESSION['request'] = "Hai ".mysqli_num_rows ($result)." nuova   richiesta di amicizia";

}

else if (mysqli_num_rows ($result) > 0) {

    echo "Hai ".mysqli_num_rows ($result)." nuove richieste di amicizia";
    $_SESSION['request'] = "Hai ".mysqli_num_rows ($result)." nuove     richieste di amicizia";

}

else if (mysqli_num_rows ($result) == 0) {

    echo "0";
    unset($_SESSION['request']);// = "Nessuna nuova richiesta";

}
disconnetti_db($mysqli);

?>

感谢大家的建议和帮助!!