如何打印有关响应内容类型 Json 的内容?

How print content about Response Content Type Json?

你好抱歉这个问题,但我不知道喜欢做我想做的事...

If i 运行 this link https://api.onwater.io/api/v1/results/10,10 API 说这个点(北纬 10°;东经 10°)是在水里还是在陆地上。

本例中的结果是:

{"lat":9.999237824938984,"lon":10.000257977613291,"water":false}

如何打印值的 water ??

非常感谢

通常您可以通过其 属性 名称访问它:

const response = {"lat":9.999237824938984,"lon":10.000257977613291,"water":false}

console.log(response.water);

假设您正在寻找一个 AJAX 调用,您可以像这样使用纯 JS

function callAjax() {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE) {   // XMLHttpRequest.DONE == 4
           if (xmlhttp.status == 200) {
               var response = JSON.parse(xmlhttp.responseText);
               document.getElementById("myDiv").innerHTML =           response.water;
           }
           else if (xmlhttp.status == 400) {
              alert('There was an error 400');
           }
           else {
               alert('something else other than 200 was returned');
           }
        }
    };

    xmlhttp.open("GET", "https://api.onwater.io/api/v1/results/10,10", true);
    xmlhttp.send();
}
callAjax();
<div id="myDiv"></div>

使用jquery会像这样

$.ajax({
    url: "https://api.onwater.io/api/v1/results/10,10",
    context: document.body,
    success: function(data){
     console.log(data.water);
    }
});

假设您通过 AJAX

检索数据
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
    if (this.readyState === 4 && this.status === 200){
        // parse the response to object
        var obj = JSON.parse(this.responseText);

        // print it out (obj.water and obj['water'] produces the same result)
        alert(obj.water);
        console.log(obj['water']); // prints it in console
    }
};
xhr.open("GET", "https://api.onwater.io/api/v1/results/10,10", true);
xhr.send();

您可以了解更多 AJAX here