我使用jquery获取示例http get请求以从DB获取json。当我执行get请求时,我从DB获取了json数组。我也试图在html页面中显示json,所以我使用jquery $(newData).html(data)
来显示json。但是我无法在html页面中看到json,<span>
标签内的单词也消失了,我觉得它试图显示整个json但是在页面上看不到它,所以需要帮助才能显示页面中的json数据。
<!DOCTYPE html>
<html>
<head>
<title>Http Get Method</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$.get("http://citibikenyc.com/stations/json",function(data, status){
$("#newData").html(data);
});
});
});
</script>
<!-- <link rel="stylesheet" type="text/css" href="getMethod.css"/> -->
</head>
<body>
<button> Get </button>
<span id="newData">
DISPLAY THE RESULT
</span>
</body>
</html>
答案 0 :(得分:0)
您可以获得如下所述的数据。
var data = '{"id": 1,"name": "test"}';
var json = JSON.parse(data);
alert(json["name"]);
alert(json.name);
答案 1 :(得分:0)
您的文字DISPLAY THE RESULT
正在消失,因为您正在使用.html
来设置所选查询的内容,即如果有任何数据,则会替换所有数据。
因此,您应该使用.append()
函数代替附加到所选查询中的现有数据。
您忘记了您获得的数据是JSON格式,并且您无法将其直接附加到页面上,通常您希望以表格格式或类似方式显示,无论如何只是为了显示在将数据附加到html页面之前,您将直接使用data = JSON.stringify(data)
数据。
替换
行 $("#newData").html(data);
与
$("#newData").append(JSON.stringify(data));
答案 2 :(得分:0)
请尝试我的解决方案让我...通过使用jsonp
<!DOCTYPE html>
<html>
<head>
<title>Http Get Method</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: "http://citibikenyc.com/stations/json",
type: "GET",
dataType: 'jsonp',
success: function (data, status, error) {
console.log(data);
data = JSON.stringify(data);
$("#newData").html(data);
},
error: function (data, status, error) {
console.log('error', data, status, error);
data = JSON.stringify(data);
$("#newData").html(data);
}
});
});
});
</script>
<!-- <link rel="stylesheet" type="text/css" href="getMethod.css"/> -->
</head>
<body>
<button> Get </button>
<span id="newData">
DISPLAY THE RESULT
</span>
</body>
</html>
&#13;