Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/442.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何为输出Json对象的ajax调用编写客户端脚本_Javascript_Html_Ajax_Json_Model View Controller - Fatal编程技术网

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

Javascript 如何为输出Json对象的ajax调用编写客户端脚本,javascript,html,ajax,json,model-view-controller,Javascript,Html,Ajax,Json,Model View Controller,当我创建ajax调用时,我通常要求使用纯HTML。 但是现在,出于几个原因,我需要关于如何在接收Json对象时构建表的建议(比如说人和他们的数据)-我知道如何用Javascript创建表-,但是因为我对服务器上的Json概念不熟悉,所以我想用正确的方法来创建表 假设我的json是这样的: [[name: foo, email:foo@bar.com ...][name:baz,...] ... []] 构建js并为其构建表的正确方法是什么。我猜会是这样的: var table = {

当我创建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 = { ... }
我的问题是:

  • 我在黑暗中行走,试图弄清楚这是否是正确的方法——是吗

  • 这里有MVC的味道-是吗?如何使用MVC模式正确构建它?假设此表需要非常交互式(大量事件和操作)

  • “有js库可以做这类事情”——我不知道从哪里开始,因为我自己很难定义我要做的到底是什么


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

    [
      { 
        propery: "some value", 
        property2: "some other value"
      },
       //.... more objects {} here
    ];
    
    在深入研究代码之前,您应该知道来自服务器的响应是字符串,所以您需要将其“编译”为javascript对象。你可以通过两种方式做到这一点

  • 使用
    JSON.parse(someString)的首选方法方法
  • 丑陋且不太可取的是使用
    eval
    Function
    方法,如
    var result=[];eval(“result=“+responseStringFromServer”)
  • 始终使用第一种方法,因为它更好,如果你不知道为什么,请检查

    既然您想使用您的类型(表、行和单元格),您应该知道它是无用的,因为JSON缺少JavaScript对象表示法,换句话说,一旦您执行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>
    
    <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>
    
    要绘制数据,可以使用以下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>"));
    }
    
    在这篇文章的最后,你应该知道有很多neath库可以简化这个过程。有些是非常适合用于复杂情况的,比如BackboneJS和AngularJs。。。。还有一些很简单,比如jQuery.template和jQuery.render,它们只是模板引擎。这取决于你的应用程序有多复杂,以及在一个页面中应该进行多少次“渲染”

    与示例abobe相同,但使用AngularJS

    可以找到工作示例

    您需要这样的页面:

    <table id="personDataTable">
        <tr>
            <th>Id</th>
            <th>First Name</th>
            <th>Last Name</th>
        </tr>
    </table>
    
    <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>
    
    
    例2
    桌子{
    边框:1px实心#666;
    宽度:100%;
    }
    th{
    背景:#f8f8;
    字体大小:粗体;
    填充:2px;
    }
    单击此处加载数据

    身份证件 名字 姓 {{person.id} //定义您的模块(应用程序) var-app=angular.module('myApp',[]); //定义负责获取数据并将结果绑定到页面的控制器 函数PeopleCtrl($scope,$http){ $scope.people=[];//这将在上面的页面模板中使用 //需要单击以获取数据的链接的事件处理程序 $scope.loadPeople=function(){ //更改链接以点击服务器json var httpRequest=$http.get(“/link/to/people.json”); //HTTP GET请求成功后,处理响应并设置新数据 httpRequest.success(函数(数据、状态){ $scope.people=数据; }); }; }​
    把你的问题往后推,我先回答#3。您可以查看一个JavaScript库,该库被调用来执行您希望执行的操作,或者即使您需要与表进行大量交互。它们都是jQuery插件

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

    最后,基于您提供的框架JS,这似乎是一种不错的方法。您将表、行和单元格拆分为单独的函数,我假设您将处理用户与表交互引发的事件。我还假设您将有
    引用
    引用
    单元格
    。这可能是一个吹毛求疵的问题,但您可能希望以相反的方向定义它们,以便JSLint不会抱怨


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

    我真的不明白你想做什么。您正在尝试在网页中构建GUI吗?请写一个小故事,描述你想用JSON做什么。我想(例如)建立一个包含我所在街道上所有人的表。我要求服务器给我一个包含所有这些人的JSON对象,然后我想用所有数据构建一个HTML表。我在问如何正确地用Javascript构建表。这给了我很多东西要研究,而这正是我想要的。谢谢!