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

时间:2016-11-11 13:05:51

标签: javascript jquery ajax xmlhttprequest

这可能是一个愚蠢的错误,但我正在使用JQuery ajax来对付PHP后端,我希望PHP脚本将进度发布回网页。

它看起来工作正常,但我无法获得e.target.responseText的内容。

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

但是,如果我执行console.log(e.target.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

3 个答案:

答案 0 :(得分:1)

仅在XMLHTTPRequest期间触发进度,而不是在收到响应时结束

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

答案 1 :(得分:0)

试试这个,

$.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.");
  }
});

答案 2 :(得分:0)

显然,在onprogress中它将为空,因为服务器在处理过程中不会返回任何数据。您只能在成功功能中阅读responseText

您可以在控制台中看到responseText的原因(即使您在onprogress中调用了.log())是因为服务器实际上已经返回了数据,并且也调用了success函数,因为您使用e.target记录整个对象,无论您在何处记录对象,该对象都可以随时更新,控制台将向您显示其实时版本,而不是控制台记录时的版本。更改对象后,它也将在控制台中的任何位置更新。但是target.responseText是一个基元,不是对象,并且控制台更改后不会更新其值。

希望这对将来的读者有所帮助。