【问题标题】:how to handle json data in javascript如何在javascript中处理json数据
【发布时间】:2015-08-13 09:04:38
【问题描述】:

我正在使用 worldweatheronline api 访问天气数据,当请求通过在 json 中发送数据发送响应时。我想在 html 页面中显示天气信息

<!DOCTYPE html>
<head>
	<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<input type="text" id="in"></input>
<input type="hidden" id="keys" value="apikey"></input>
<button id="go">Search</button>
<script>
$(document).ready(function(){
$("#go").click(function(){
	var apikey = $("#keys").val();
	var q = $("#in").val();
jQuery.ajax({
    url: 'http://api.openweathermap.org/data/2.5/weather?key=' + apikey + '&q=' + q,
    success: function(response){
        var obj = JSON.parse(response);
        console.log(obj);
    },
    });
 });
});
</script>
</body>
</html>
<html>
<head>
    <title>weather app</title>
</head>
<body>
    <form method="GET" action="http://api.openweathermap.org/data/2.5/weather">
        <input type="hidden"  name="key" value="apikeyneeded"></input>
        <input type="text" name="q"></input>

        </form>
        </body>
</html>

【问题讨论】:

    标签: javascript html json xml


    【解决方案1】:

    检查一下。

    var apikey = jQuery('[name="key"]').val();
    var q= jQuery('[name="q"]').val();
    jQuery.ajax({
        url: 'http://api.openweathermap.org/data/2.5/weather?key=' + apikey + '&q=' + q,
        success: function(response){
            var obj = JSON.parse(response);
            console.log(obj);
        },
    });
    

    将此行添加到head 标记中以包含jQuery &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"&gt;&lt;/script&gt;

    【讨论】:

      【解决方案2】:

      使用 ajax 方法从 openweathermap api 获取数据。

      $.ajax({
              url: "http://api.openweathermap.org/data/2.5/weather?key=apikey&q=delhi",
              dataType: "jsonp", //Handle ajax cross domain
              success: function (response) {
                  //the response already parsed.
      
              }
          });
      

      【讨论】:

        【解决方案3】:

        您不能那样使用JSON.parse。首先,您必须向该 API 发出请求,然后获得响应,最后使用解析 JSON.parse(response) 如果您有兴趣,我可以帮助您使用 jQuery 来请求 json 来管理它。

        【讨论】:

        • 你能解释一下如何在jquery中做到这一点
        • 检查我的答案,如果它有效,那么我可以帮助您从 obj JSON 对象中获取值。
        • 如何解析json数据@Hovo
        猜你喜欢
        • 1970-01-01
        • 2023-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-01
        • 1970-01-01
        • 2017-01-01
        相关资源
        最近更新 更多