簡體   English   中英

使用javascript / jquery從API獲取Json響應

[英]Getting Json Response from an API using javascript/jquery

我是javascript和jquery的新手,並且在使用jquery解析json時遇到問題。 我正在使用開放天氣最簡單的API來獲取天氣信息,但沒有任何反應。 如果我將json硬編碼在任何文件或腳本中,則可以正常工作,但是一旦我使用API​​的URL,它就會停止顯示結果。

這是我完整的代碼:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
    function myFunction() {
        var path = "api.openweathermap.org/data/2.5/weather?q=Lahore,pk";
        $(document).ready(function () {
            $("button").click(function () {
                $.getJSON(path, function (data) {
                    $.each(result, function (i, field) {
                        $("div").append(field + " ");
                    });
                });
            });
        });
    }
</script>
</head>
<body>

<button onclick="myFunction()">Get JSON data</button>

<div></div>

</body>
</html>

遍歷JSON結果,即。 您的data

工作代碼:

<button>Get JSON data</button>
<div></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
    var path = "http://api.openweathermap.org/data/2.5/weather?q=Lahore,pk";
        $(document).ready(function () {
            $("button").click(function () {
                $.getJSON(path, function (data) {
                    $.each(data, function (i, field) {
                        $("div").append(JSON.stringify(field)); // parse the object according to your need.
                    });
                });
            });
        });
</script>

您犯了多個錯誤。 這是一個工作的小提琴:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">    </script>
</head>
<body>

<button id="myButton">Get JSON data</button>

<div id="mydiv"></div>

</body>
<script>
$("#myButton").click(function(){
    var path = "http://api.openweathermap.org/data/2.5/weather?q=Lahore,pk";
    $.getJSON(path, function (data) {
        $.each(data, function (i, field) {
            var textNode = document.createTextNode(i+ " " +JSON.stringify(field));
            $("#mydiv").append(textNode);
        });
    });
});
</script>

如果您需要更多信息,請寫評論。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM