簡體   English   中英

使用JavaScript和AJAX將OnClick事件轉換為定時事件

[英]Turning an OnClick Event Into A Timed Event with JavaScript & AJAX

我目前正在使用AJAX和JavaScript進行學習。

我對智者有一個簡單的問題。

如何將下面的代碼轉換為定時事件而不是OnClick事件。

**例如,我想每5秒刷新一次“顯示列表” DIV ...

我知道這是有效的代碼,並且違反了網站的規則,但是如果我張貼我的非有效代碼,那只會使我感到困惑。

我試圖慢慢地了解基本知識:)

任何指導將不勝感激

<!DOCTYPE html>
<html>
<head>
<script>

function loadXMLDoc()
{

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

xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
{

document.getElementById("showlist").innerHTML=xmlhttp.responseText;

}
}

xmlhttp.open("GET","playlist.php?t=" + Math.random(),true);
xmlhttp.send();

}
</script>
</head>

<body>
<h2>Ajax Testing...</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="showlist"></div>
</body>

</html>

您可以更改loadXMLDoc函數以使用setTimeout 考慮以下示例:

function loadXMLDoc() {

    var xmlhttp,
        timer;

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

    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("showlist").innerHTML = xmlhttp.responseText;
        }
    };

    xmlhttp.onerror = function() {
        clearTimeout(timer);
    };

    xmlhttp.open("GET", "playlist.php?t=" + Math.random(), true);
    xmlhttp.send();


    timer = setTimeout(loadXMLDoc, 5000);
}

函數發出AJAX請求並設置5s超時。 我還添加了基本的onerror回調以清除計時器,以防萬一。

我曾經做過一種電視,可在3秒鍾后自動更改“屏幕”。

也許您可以重用我的代碼?

// This is the div called myScreen
var myScreen = document.getElementById('myScreen');
// This is an array, which is holding the names of the pictures
var myPics = ['img-screen1.png','img-screen2.png'];
// This is looking at how many things the array holds
var totalPics = myPics.length;
// Now this is where the magic begins, this keeps looping around and around, and 
// makes sure all the pictures are being showed, one by one.
var i = 0
function loop() {
    if(i > (totalPics - 1)){
        i = 0;
    }
    myScreen.innerHTML = '<img src="images/'+myPics[i]+'">';
    i++;
    loopTimer = setTimeout('loop()',3000);
}
loop();

我希望您可以將其重新用於您的項目,希望您能理解我的意思,如果需要澄清,請問我:)。

因此,您需要做的就是在顯示清單中有新商品時刷新陣列。

該函數(如果在loadXMLDoc fn之后放置在相同的腳本標記中)將執行並調用您的函數,然后每5秒(遞歸)再次調用該函數。 您可以調用setInterval,但是如果js引擎繁忙,則可能會偶爾丟失一個循環:

(function doMeSelf(){
    setTimeout(function(){
        loadXMLDoc();
        doMeSelf();
    },5000);
})();

將函數def封裝在parens中,然后緊跟(),稱為立即調用的函數表達式。

請參閱以下問題以了解某些背景信息: 對象/函數/類聲明周圍的括號是什么意思?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM