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