无法从XHR对象获取responseText

时间:2019-08-23 13:08:16

标签: javascript

我想从php获取响应文本。我在控制台中将其视为“ responseText”,但无法从函数代码变量中获取。

运行这段代码console.log(query(path,"GET"))时,我在屏幕截图中看到了响应。当我运行这段代码console.log(query(path,"GET").responseText)时,只能看到空白的响应。

PHP代码

<?php echo "Hi this is PHP Answer from Async XHR  request "; ?>

JavaScript代码

query=function(url,method){
    xhr=new XMLHttpRequest()
    xhr.url=url
    xhr.open(method,url,true)
    xhr.send()
    return xhr;
}

path="../../core/ajax/periyodikTarama.php"
console.log(query(path,"GET"))

控制台结果

查看选中的红色文本

enter image description here

1 个答案:

答案 0 :(得分:0)

未经测试,但这是处理带有回调的异步响应的正确方法。

query = function(url, method, callbackFn) {
  xhr = new XMLHttpRequest();
  xhr.url = url;
  xhr.open(method, url, true);
  xhr.onload = () => {
    callbackFn(xhr.responseText); // Feed the response to the callback
  }
  xhr.send();
  return xhr;
}

path = "../../core/ajax/periyodikTarama.php"
query(path, "GET", (responseText) => {
  console.log(responseText); // Log the resonse text
})