【问题标题】:How to obtain the body response in the client-side?How to obtain the body response in the client-side?
【发布时间】:2022-12-01 14:12:42
【问题描述】:

I am new in web, I am serving an html when a button is clicked on the client side through a request, the body response of that request is the html. How can I retrieve the html or body response from the client side?

I am trying with this code but everything is empty:

 var xhr = new XMLHttpRequest();
 xhr.open(signedRequest.method, signedRequest.url, true);
 console.log('xhr.response: ', xhr.response);
 console.log('xhr.responseText: ', xhr.responseText);
 console.log('xhr.responseXML: ', xhr.responseXML);
 document.write('<p>xhr: ' + xhr + '</p>');
 xhr.send();

Any idea on how to obtain the body response in the client-side?

【问题讨论】:

  • So the responseText does not have the content? Are you running into CORS problem?
  • Note: synchronous requests are a bad idea. You should ideally use fetch.
  • Thanks @epascarello for your cmets, I'm not running into CORS problem, the html is served but I can't obtain the body response. I'll switch to fetch, thanks.
  • So the responseText has no content?
  • @frankh07 Did you have a look at the answer I provided?

标签: javascript html http xmlhttprequest response


【解决方案1】:

Try to add a div or any input element with the id "demo" and try to run the code below.

var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
   if (this.readyState == 4 && this.status == 200) {
        document.getElementById("demo").innerHTML = "<strong>The response from the test URL is: </strong>" + this.responseText;
        console.log(JSON.parse(this.response));
   }
};
xhttp.open("GET", "https://httpbin.org/get", true);
xhttp.send();
&lt;div id="demo"&gt;&lt;/div&gt;

【讨论】:

  • Happy to help! Enjoy your coding!
  • Sorry @Dream Bold i´m having issues with XMLHttpRequest request, maybe do you know how to obtain the body response from a fetch request? I'm tryng with .then((response) => {console.log(response.body); }) but didn't work.
猜你喜欢
  • 2022-12-01
  • 2022-12-02
  • 2022-12-27
  • 2022-12-02
  • 2022-12-02
  • 2022-12-26
  • 2022-12-01
  • 2022-12-01
  • 2022-12-31
相关资源
最近更新 更多