在 JavaScript 中使用 window.alert
或 alert
显示 JSON 响应时遇到问题。我不是一个原生的 JS 编码员,对于我的菜鸟行为我深表歉意。以下是我根据网上找到的示例尝试的一些示例。
我的目标是让 JSON 响应出现在警报弹出窗口中。
# example 1
<script type="text/javascript">
var client = new HttpClient();
client.get('https://website.com/json/', function(response) {
window.alert(response);
});
</script>
# example 2
$.get('https://website.com/json/', function(responseText) {
alert(responseText);
});
# example 3
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
$.get('https://website.com/json/', function(responseText) {
alert(responseText);
});
</script>
# example 4
var xhr = new XMLHttpRequest();
xhr.open('GET', "https://website.com/json/", true);
xhr.send();
xhr.onreadystatechange = processRequest;
function processRequest(e) {
}
最佳答案
我看到的第一个问题是 url https://website.com/json没有正确的回应。
例如,您可以尝试以下链接:https://jsonplaceholder.typicode.com/posts/1 或https://ipinfo.io/json
我证明了你的示例 4,它运行得很好。
var xhr = new XMLHttpRequest();
xhr.open('GET', "https://jsonplaceholder.typicode.com/posts/1", true);
xhr.send();
xhr.onreadystatechange = processRequest;
function processRequest(e) {
var response=JSON.stringify(e);
alert(response);
}
您可以注意到我将警报放在 processRequest 函数中并在显示之前。我使用 JSON.stringify 将对象 e 更改为字符串。让我知道这是否适合你。
关于javascript - 如何在警报窗口中显示 HTTP 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48967325/