简体   繁体   中英

how to handle json data in javascript

I am using worldweatheronline api to access weather data,when a request is send it response by sending data in json.I want to display the weather information in html page

 <!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>

You can't use the JSON.parse that way. At first you must make a request to that API, then get a response and finally use the parse JSON.parse(response) if you are interested I can help you to manage this using jQuery to request the json.

Check this.

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);
    },
});

add this line into the head tag to include jQuery <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

Use ajax method to get the data from 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.

        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM