在JSFiddle中使用Angular创建JSON表

JSON table creation with Angular in JSFiddle

本文关键字:创建 JSON Angular JSFiddle      更新时间:2024-06-19

尝试获得一些JSON和Angular.js来解决任何问题。我使用以下代码,但当单击"单击此处"时,它似乎不会运行loadpeople函数。可能错过了一些愚蠢的东西。

HTML

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Render json in table using AngularJs - jsFiddle demo by mjaric</title>

      <link rel="stylesheet" type="text/css" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
      <script type='text/javascript' src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
      <script type='text/javascript' src="loadpeople.js"></script>
      <script type='text/javascript' src="http://code.angularjs.org/1.0.1/angular-1.0.1.min.js"></script>

  <style type='text/css'>
    table {
  border: 1px solid #666;   
    width: 100%;
}
th {
  background: #f8f8f8; 
  font-weight: bold;    
    padding: 2px;
}
  </style>
</head>
<body>
  <div ng-app="myApp">
<div ng-controller="PeopleCtrl">
    <p>    Click <a ng-click="loadPeople()">here</a> to load data.</p>
<table>
    <tr>
        <th>Id</th>
        <th>First Name</th>
        <th>Last Name</th>
    </tr>
    <tr ng-repeat="person in people">
        <td>{{person.id}}</td>
        <td>{{person.firstName}}</td>
        <td>{{person.lastName}}</td>
    </tr>
</table>
</div>
</div>
</body>

</html>

JS

var mockDataForThisTest = "json=" + encodeURI(JSON.stringify([
    {
    id: 1,
    firstName: "Peter",
    lastName: "Jhons"},
{
    id: 2,
    firstName: "David",
    lastName: "Bowie"}
]));

var app = angular.module('myApp', []);
function PeopleCtrl($scope, $http) {
    $scope.people = [];
    $scope.loadPeople = function() {
        var httpRequest = $http({
            method: 'POST',
            url: '/echo/json/',
            data: mockDataForThisTest
        }).success(function(data, status) {
            $scope.people = data;
        });
    };
}

我在这个fiddle中使用了您的代码,使示例工作得很好:http://jsfiddle.net/4w6Uv/3.我还使用一个简单的node.js服务器重复了这个例子,这次它通过将mockdata切换到一个直数组来工作,所以:

mockData = [{
    id: 1,
    firstName: "Peter",
    lastName: "Jhons"},
{
    id: 2,
    firstName: "David",
    lastName: "Bowie"}
];

还值得一提的是,在您的示例中实际上并不需要jQuery(除非您没有提供的其他代码使用它)。你的帖子没有标记Angular,这可能有助于引出更多答案。被调用的函数由Angular控制器提供,而不是与jQuery有任何关系(如果这是已知的,请道歉)。

快速检查显示您的成功函数从未被调用。你确定你能发布到"/echo/json/"吗?