【问题标题】:JQuery and Ajax to get the response Line by LineJQuery 和 Ajax 逐行获取响应
【发布时间】:2024-01-07 05:38:02
【问题描述】:

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

  $.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 中?

【问题讨论】:

  • 我猜你打了多个 AJAX 调用。如果是这样,“需要时间的行动”就不会花时间完成。
  • 我猜您正在搜索的是流式响应。这个GIST 链接可能会对您有所帮助。

标签: javascript jquery ajax httprequest httpresponse


【解决方案1】:

您可以使用promise api 来生成此行为。这是想法。您首先使用 ajax 请求获取文本数据。ajax 旨在返回一个 Promise。然后使用 Promise 链将数据按每一行拆分,并在一定的延迟后打印出来以模拟延迟

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

【讨论】:

  • .then(data=>data.split('\n')) wtf ? javascript 1.1 请,
  • data=>data.split('\n') 是一个箭头函数,它已作为回调传递给 promise 的 'then' 方法。我希望这就是你问我是否理解正确
最近更新 更多