javascript 检索 Post Request 响应并存储到变量中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7674134/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 00:53:10  来源:igfitidea点击:

Retrieving the Post Request response and storing into a variable?

javascripthtmlhttp-post

提问by Max

So I have the below code:

所以我有以下代码:

    var formData = new FormData();  
    formData.append("title", document.getElementById("title").value);  
    formData.append("html",my_html);  

    var xhr = new XMLHttpRequest();  
    xhr.open("POST", "https://www.mywebsite.com/index");  
    xhr.send(formData); 
    xhr.onreadystatechange = function() { 
      // If the request completed, close the extension popup
      if (req.readyState == 4)
        if (req.status == 200) window.close();
    };

The server is supposed to send back a response in JSON format. How do I retrieve and store that in a variable?

服务器应该以 JSON 格式发回响应。如何检索并将其存储在变量中?

回答by marcocamejo

If the answer is in JSON, you have the result in the responseText attribute.

如果答案是 JSON,则结果在 responseText 属性中。

if (xhr.readyState == 4)
  if (xhr.status == 200)
    var json_data = xhr.responseText; 

For more details, view: XMLHttpRequest

更多详情请查看:XMLHttpRequest

回答by Janis Lankovskis

回答by 1' OR 1 --

Just use xhr.responseTextto get the response of the request. You can also use xhr.responseXMLto retreive a DOM-compatible document object of the response, that means you can access it like document.

仅用于xhr.responseText获取请求的响应。您还可以使用xhr.responseXML检索响应的 DOM 兼容文档对象,这意味着您可以像document.

Source: http://developer.apple.com/internet/webcontent/xmlhttpreq.html

来源:http: //developer.apple.com/internet/webcontent/xmlhttpreq.html