2017-04-05 92 views
0

使用jQuery获取示例http获取请求从数据库获取json。当我执行get请求时,我从DB获得了json数组。另外我试图在HTML页面中显示json,所以我用jquery $(newData).html(data)来显示json。但我无法看到HTML页面中的json,<span>标签中的单词也消失了,我觉得它试图显示整个json,但它在页面上看不到,所以需要帮助显示json数据。页。如何使用jQuery显示从数据库获取到HTML页面

<!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); 
0

您的文字DISPLAY THE RESULT正在消失,因为你正在使用.html该设置将选择查询的内容,即它取代,如果有任何的任何数据。

因此,您应该使用.append()函数代替追加到选定查询中的现有数据。

你忘记了你得到的数据是JSON格式,你不能直接附加到页面,一般你想以表格格式或类似的东西显示,无论如何只是为了显示数据在将其追加到html页面之前,您正在直接使用data = JSON.stringify(data)

$("#newData").append(JSON.stringify(data));

0

替换行

$("#newData").html(data);

请尝试我的解决方案,让我..通过使用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>

+0

此错误即将发布,因为stackoverflow拒绝从其控制台加载其他网址数据,尽管它可以在本地机器上正常工作 – warl0ck

+0

感谢您的信息:-) –

相关问题