[英]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.