【问题标题】:How to write client side scripts for ajax call that outputs Json object如何为输出 Json 对象的 ajax 调用编写客户端脚本
【发布时间】:2012-08-15 07:42:36
【问题描述】:

当我创建 ajax 调用时 - 我通常要求纯 HTML。 但是现在,出于几个原因,我需要关于如何构建表格的建议(比如说人员及其数据)接收 Json 对象时 - 我知道如何创建一个Javascript 中的表格 - 但由于我对 Json-from-server 这个概念不熟悉,所以我想以正确的方式进行操作

假设我的 json 是这样的:

[[name: foo, email:foo@bar.com ...][name:baz,...] ... []]

什么是构建js为其构建表的正确方法。我猜它会像这样:

var table = {
    init : function() {..}
    new : function(Json) {..} 
    delete : function(Json) {..}
}

var row = {
    init : function() {..}
    new : function(rowParam) {..}
}

var cell = { ... }

我的问题是:

  1. 我在黑暗中行走,试图弄清楚这是否是正确的方式 - 是吗?

  2. MVC 有什么味道 - 是吗?如何使用 MVC 模式正确构建它?假设这张表需要非常互动(大量的事件和操作)

  3. 1234563 /p>

【问题讨论】:

  • 我不太明白你想做什么。您是否尝试在网页中构建CRUD GUI?请写一个小故事,描述你想用那个 JSON 做什么。
  • 我想构建(例如)一个包含所有住在我街道上的人的表。我要求服务器给我一个包含所有这些人的 JSON 对象,然后我想构建一个包含所有数据的 HTML 表。我在问如何正确使用 Javascript 构建表格。

标签: javascript html ajax json model-view-controller


【解决方案1】:

根据您的问题,我将首先回答 #3。您可以查看一个名为 DataTables 的 JavaScript 库来做您想做的事情,或者如果您需要与您的表进行大量交互,甚至可以查看 jqGrid。它们都是 jQuery 插件。

如果您有很多事件和操作正在进行,听起来您正在寻找更多的 MVVM 方法,有点像 KnockoutJSEmber 或其他一些库。但是根据您提供的内容,我不确定您是否遵循 MVC 方法。

最后,根据您提供的骨架 JS,这似乎是一种不错的方法。您将表格、行和单元格分解为单独的函数,我假设您将在其中处理用户与表格交互所引发的事件。我还假设您将拥有 table 引用 rowrow 引用 cell。这可能是一个挑剔的选择,但您可能希望以相反的方向定义它们,以便 JSLint 不会抱怨。

我希望这会有所帮助。如果您有问题,我可以进一步详细说明。祝你好运!

【讨论】:

  • 这给了我很多要研究的东西,而这正是我所寻找的。非常感谢!
【解决方案2】:

首先,我需要更正您的 json 格式。由于您正在处理对象格式的数组是

[
  { 
    propery: "some value", 
    property2: "some other value"
  },
   //.... more objects {} here
];

在我们深入研究代码之前,您应该知道来自服务器的响应是字符串,因此您需要将其“编译”为 javascript 对象。你可以通过两种方式做到这一点

  1. 使用JSON.parse(someString);方法的首选方式
  2. 丑陋且不太理想的是使用evalFunction方法,如var result=[]; eval("result=" + responseStringFromServer);

始终使用第一种方法,因为它更好,如果您不知道为什么,请查看this link

既然你想使用你的类型(表格、行和单元格),你应该知道它是无用的,因为 JSON 缺少 JavaScript 对象表示法,换句话说,一旦你这样做了 var myArray= JSON.parse(responseFromServer); myArray 将是一个 JavaScript 数组,每个item 是 Javascript 对象。如果您不需要知道下属类型是什么,请不要将其转换为您的对象

可以在here找到工作示例 这是它的工作原理

您的数据需要 html 中的占位符,可以说它看起来像这样:

<table id="personDataTable">
    <tr>
        <th>Id</th>
        <th>First Name</th>
        <th>Last Name</th>
    </tr>
</table>

假设我们从这样的 ajax 得到结果

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

要绘制数据,您可以使用这 3 种方法

// This will iterate over each result in array (as you mentioned the javascript table)
function drawTable(data) {
    for (var i = 0; i < data.length; i++) {
        // call method to draw each row
        drawRow(data[i]);
    }
}

function drawRow(rowData) {
    // create html table row
    var row = $("<tr />")
    // append it to HTML teable element
    $("#personDataTable").append(row); 
    // append each cell to row html element with data in it
    row.append($("<td>" + rowData.id + "</td>"));
    row.append($("<td>" + rowData.firstName + "</td>"));
    row.append($("<td>" + rowData.lastName + "</td>"));
}

最后,你的 ajax 调用(当然使用 jQuery)

$.ajax({
    url: '/echo/json/',
    type: "post",
    dataType: "json",
    data: {
        //... pass here any data you want to your server
    },
    success: function(data, textStatus, jqXHR) {
        // since we are using jQuery, you don't need to parse response
        drawTable(data);
    }
});

在这篇文章的最后,您应该知道那里有许多可以简化此过程的整洁库。有些确实适合用于复杂的情况,例如 BackboneJS 和 AngularJs .... 有些很简单,例如 jQuery.template 和 jQuery.render,它们只是模板引擎。这取决于您的应用有多复杂,以及在单个页面中应该发生多少“渲染”。

与上面的示例相同,但使用 AngularJS

可以在here找到工作示例

你需要这样的页面:

<html ng-app="myApp">
<head>
<title>Example 2</title>
<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>
<!-- Assign Controller to element, it will handle the "data scope" and events of ineer elements -->
<div ng-controller="PeopleCtrl">
     <!-- Example of attaching event handler to link click event -->
    <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>
    <!-- here is how to receptively render array of object using ng-repeat directive. Note that you have defined people attribute in $scope object, it is bound to this template below --> 
    <tr ng-repeat="person in people">
        <td>{{person.id}}</td> <!-- bind single attribute -->
        <td ng-template="{{person.firstName}} {{person.lastName}}"></td> <!-- binding 2 attributes to same element using ng-template directive -->
    </tr>
</table>
</div>
<script type="text/javascript">
// define your module (application)
var app = angular.module('myApp', []);
// define controller responsible to get data and bind result to page
function PeopleCtrl($scope, $http) {

    $scope.people = []; //this will be used in page template above
    // event handler for link which you need to click in order to get data  
    $scope.loadPeople = function() {
        // change link to hit your server json
        var httpRequest = $http.get("/link/to/people.json");
        // on success of HTTP GET request above handle response and set new data
        httpRequest.success(function(data, status) {
            $scope.people = data;
        });

    };

}​
</script>

</body>
</html>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-12
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多