JQuery and Ajax to get the response Line by Line

耗尽温柔 提交于 2020-03-03 09:59:10

问题


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 
 });

Lets say I get the following response,

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

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?


回答1:


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)
            })
        }  
    } 


来源:https://stackoverflow.com/questions/49150264/jquery-and-ajax-to-get-the-response-line-by-line

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!