簡體   English   中英

是否可以檢索 jQuery ajax 響應,然后通過遍歷數組添加數據的打印延遲

[英]Is it possible to retrieve an jQuery ajax response, then adding a print delay of data by iterating through an array

在典型的 ajax 響應中,您只需將數據打印到 div 即可。 我想獲取數據響應並將其拆分為一個數組,然后迭代該數組並在附加之間添加一個隨機延遲。

在這個特定示例中,我將響應拆分為每個

標簽。 然后我希望在打印這些響應之前添加延遲。

到目前為止,這對我不起作用。 即使我使用 setTimeout 遍歷數組,它也只會完整展示數據響應。

        //start the ajax
        $.ajax({
            //this is the php file that processes the data and send mail
            url: "/a_example.php?sim",  
            target:    '#crap',   // target element(s) to be updated with server response 
            //GET method is used
            type: "POST",

            //pass the data         
            data: data,     

            //Do not cache the page
            cache: false,

    success: function(data) {
                  var patt = /<p>(.*?)<\/p>/g;
                  var result = data.match(patt);
                var i;
                //alert(result.length);
                for (i = 0; i < result.length; i++) {
                    showResultMock(result[i]);

                }               


    },                  

    complete: function() {

        }

        });

function showResultMock(result){
 setTimeout(function(){  $('#modaldraftdetails .modal-body .draft-results').append(result); }, 2000);
}   

嘗試使用遞歸而不是迭代。 像這樣的東西:

const $resultsContainer = $('#results')
const results = [1,2,3]

function showResults(results) {
  if (!results.length) return
  setTimeout(function(){
    const result = results.shift()
    $resultsContainer.append(`<p>${result}</p>`)
    showResults(results)
  }, 2000)
}

showResults(results)

您可以遞歸地使用function並使用Math.random()添加隨機延遲,如下所示:

 let ctn = $("#ctn"), results = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], i = 0, maxDelay = 2000; const printVal = val => { if (i < results.length) { //console.log(val); ctn.append(`<span>${val}</span>`) setTimeout(() => { i++; printVal(results[i]); }, Math.random() * maxDelay) } } printVal(results[i])
 span{ margin: 5px; font-family: courier; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="ctn"></div>

當您遍歷結果時,您基本上會同時創建一組 setTimeouts。 因此,那些 setTimeouts 也同時完成。

嘗試遞歸解決方案,如下所示:

/* Put this into the "success" callback */
var results = data.match(patt);
showResultMock(results, 0);

/* And this is your recursive fucntion's definition */
function showResultMock(results, i){
    if (i < results.length) {
        setTimeout(function(){  
            $('#modaldraftdetails .modal-body .draft-results').append(results[i]);
            showResultMock(results, ++i);
        }, 2000);
    }
}   

暫無
暫無

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

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