jQuery和Ajax逐行获取响应 [英] JQuery and Ajax to get the response Line by Line

查看:135
本文介绍了jQuery和Ajax逐行获取响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过jQuery进行Ajax调用,如下所示.

I am making an Ajax call through jQuery as follows.

  $.ajax({
       type:"GET",
       cache:false,
       url:"SomeURL",
       data:{
            input : some_var,
       },    // multiple data sent using ajax.
       async: false,
       success: function (response) {
         console.log("Success");
         $("#progress-textarea").append(response + "\n");
       },//sucess
       failure: function (response) {
          console.log("Failure");
          $("#progress-textarea").append("Failed to Execute " + final_command + "\n");
       }//fail if anything wrong happens 
 });

让我说以下答复,

This is line 1
// Performing some action that takes time..
This is line 2
// Performing some action that takes time..
This is line 3
// Performing some action that takes time..
This is line 4
// Performing some action that takes time..
This is line 5
// Performing some action that takes time..
This is line 6
// Performing some action that takes time..
This is line 7
// Performing some action that takes time..
This is line 8
// Performing some action that takes time..
This is line 9
// Performing some action that takes time..
This is line 10

我一口气得到了回应. 我将响应附加到文本框以显示执行进度. 如何实现Ajax调用,以便逐行获取响应并将每行立即添加到textarea中?

I am getting the response in one go, all together. I am appending the response to a textbox to show some progress of execution. How can I implement the Ajax call so as to get the response line by line and append each line into the textarea immediately?

推荐答案

您可以使用promise api来产生这种行为.首先,您需要使用ajax请求获取文本数据.ajax旨在返回一个Promise,然后使用Promise链按每行拆分数据,并在经过一定的延迟后将它们打印出来,以模仿延迟

You can use promise api to generate this behavior.Here is the idea. You first fetch text data using ajax request.The ajax is designed to return a promise.Then use promise chain to split the data by each line and print them out after a certain amount of delay to mimic a delay

    function fetch(){
        return new Promise((resolve,reject)=>{
            let http = new XMLHttpRequest()
            http.onreadystatechange = function(){
                if(http.readyState == 4 && http.status == 200){
                   resolve('this is line 1\nthis is line 2') // suppose this is your response from server
                }
            }
            http.open('GET','sample.txt',true)
            http.send()
        })
    }

    fetch()
    .then(data=>data.split('\n'))
    .then(delay())
    .then(delay())

    function delay(){
        return function(data){
            return new Promise(resolve=>{         
               setTimeout(()=>{console.log(data[0]);data.shift();resolve(data)},2000)
            })
        }  
    } 

这篇关于jQuery和Ajax逐行获取响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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