responseText为空,但显示在控制台上

responseText is empty, but shows on console?

本文关键字:控制台 显示 为空 responseText      更新时间:2023-09-26

这可能是一个愚蠢的错误,但我使用JQuery ajax对PHP后端,我想PHP脚本张贴进度回网页。

它看起来工作得很好,但我不能得到e.g target. responsetext的内容。

如果执行console.log(e.target),我将在控制台中获得XMLHttpRequest对象。我可以看到responseText: "1 av 1500 "

但是如果我执行console.log(e.a rtarget . responsetext),它是空的。

我疯了吗?

这是我的功能

$.ajax(
    {
        type: "POST",
        url: "modEcs/ajax/ecs.php?a=analyseExcel",
        processData: false,
        contentType: false,
        xhrFields: 
        {
        onprogress: function(e) 
        {               
            console.log(e.target);
            console.log(e.target.responseText);  
            }
        },
        success: function(data) 
        {
         },
         error: function (xhr, ajaxOptions, thrownError) { alert(xhr.statusText); }
    });

控制台数据:

XMLHttpRequest
onabort: null
onerror: null
onload: null
onloadend: null
onloadstart: null
onprogress: function(e)
onreadystatechange: null
ontimeout: null
readyState: 4
response: "1 av 1500 linjer"
responseText: "1 av 1500 linjer"
responseType: ""
responseURL: "xxx"
responseXML: null
status: 200
statusText: "OK"
timeout: 0
upload: XMLHttpRequestUpload {onloadstart: null, onprogress: null, onabort: null, onerror: null, onload: null, …}
withCredentials: false
XMLHttpRequest-prototype

progress仅在XMLHTTPRequest期间触发,而不是在收到响应的最后触发

readyState 3: "Downloading; responseText holds partial data."

试试这个,

$.ajax({
     type: "POST",
     url: "modEcs/ajax/ecs.php?a=analyseExcel",
     processData: false,
     contentType: false,
     xhr: function(){
        var xhr = new window.XMLHttpRequest();
        // Handle progress
        xhr.addEventListener("progress", function(evt){
        //Do some progress calculations
          console.log(xhr.responseText);
     }, false);
   return xhr;
  },
  complete:function(){
    console.log("Request finished.");
  }
});

显然在onprogress中它将是空的,因为服务器在进程期间不返回任何数据。你只能在success函数中读取responseText

你可以在控制台看到responseText的原因(即使你在onprogress中调用.log()),是因为服务器实际上已经返回了数据,并调用了success函数,因为你正在用e.target记录整个对象,对象可以随时更新,无论你在哪里记录它,控制台都会显示你的实时版本,而不是在控制台日志记录的确切时刻的版本。当对象被更改时,它也会在控制台的任何地方更新。但target.responseText是一个原语,它不是一个对象,控制台不会更新它的值时,它的变化。