I am newbie with javascript and jquery and i am facing a problem in json parsing with jquery. I am using open weather simplest API for fetching the weather information but nothing is happening. If i hardcode the json in any file or in my script it works fine but as soon as i use URL of API it stop showing result.
here is my complete code:
<!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>
Loop through the JSON result, ie. data
in your case, :
Working Code:
<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>
You did multiple mistakes. Here a working fiddle:
<!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>
Write a comment if you need more information.
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.