如何为输出Json对象的ajax调用编写客户端脚本

How to write client side scripts for ajax call that outputs Json object

本文关键字:调用 客户端 脚本 ajax 输出 Json 对象      更新时间:2023-09-26

当我创建ajax调用时,我通常要求纯HTML。但现在,由于几个原因,我需要关于如何构建表的建议(比如人员和他们的数据)当接收Json对象时-我知道如何用Javascript创建表,但由于我是服务器上Json概念的新手,我想以正确的方式来做

假设我的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. "有些js库也在做这类事情"——我不知道从哪里开始,因为很难为自己定义我要做的到底是什么。

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

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

最后,基于您提供的骨架JS,这似乎是一种不错的方法。您正在将表、行和单元格分解为单独的函数,我假设您将在其中处理用户与表的交互所引发的事件。我还假设table引用rowrow引用cell。这可能是一个挑剔的地方,但您可能想从相反的方向定义它们,这样JSLint就不会抱怨了。

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

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

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

在深入研究代码之前,您应该知道来自服务器的响应是字符串形式的,所以您需要将其"编译"为javascript对象。有两种方法

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

总是使用第一个通道,因为它更好,如果你不知道为什么,请检查这个链接

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

工作示例可在此处找到以下是的工作原理

你需要在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

工作示例可以在这里找到

你需要这样的页面:

<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>