【问题标题】:How print content about Response Content Type Json?如何打印有关响应内容类型 Json 的内容?
【发布时间】:2018-04-04 01:17:07
【问题描述】:

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

如果我运行此链接https://api.onwater.io/api/v1/results/10,10 API,则说明此点(北纬 10°;东经 10°)是在水中还是在陆地。

这种情况下的结果是:

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

如何打印值的water ??

非常感谢

【问题讨论】:

  • 我可以假设您从 AJAX 请求中检索数据吗?
  • 我希望...你能告诉我一个例子或链接吗?感谢您的建议

标签: javascript json httpresponse content-type


【解决方案1】:

假设你正在寻找一个 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);
    }
});

【讨论】:

    【解决方案2】:

    通常你可以通过它的属性名来访问它:

    const response = {"lat":9.999237824938984,"lon":10.000257977613291,"water":false}
    
    console.log(response.water);

    【讨论】:

      【解决方案3】:

      假设您正在通过 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

      【讨论】:

        猜你喜欢
        • 2011-01-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-03-20
        • 1970-01-01
        • 2010-09-28
        • 2019-01-01
        相关资源
        最近更新 更多