【问题标题】:Getting data from JSON array in a table从表中的 JSON 数组中获取数据
【发布时间】:2015-03-15 16:35:19
【问题描述】:

如果一个网站给出json数组数据如下

mycallback([{"id":"2","name":"Kelly","age":"12"},{"id":"3","name":"Robby","age":"12"}])

我如何将此json 数组数据称为表格

我的尝试,但没有奏效!

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
    $('#example').dataTable( {
        "processing": true,
        "serverSide": true,
        "ajax": {
            "url": "http://WebSite_URL.com/data.php",
            "dataType": "jsonp",
            "jsonp":"mycallback"

        }
    } );
} );
</script>

<table id="example" cellspacing="0" width="100%">
<tr>
<th>ID</th>
<th>Name</th>
<th>Age</th>
</tr>
</table>

【问题讨论】:

  • 任何答案都解决了您的问题吗?

标签: javascript jquery json jsonp


【解决方案1】:

默认情况下,DataTables 期望数据源包含在名为 data 的变量中,如下所示:

{data:[{"id":"2","name":"Kelly","age":"12"},{"id":"3","name":"Robby","age":"12"}]}

但是,在您的情况下,我假设更改 json 格式不是一个选项,因为它是 Jsonp 请求。因此,我假设您的数据被格式化为“平面”数组,并且不能像这样更改:

[{"id":"2","name":"Kelly","age":"12"},{"id":"3","name":"Robby","age":"12"}]

现在,通过将ajax 数组中的dataSrc 选项作为空白值,dataTables 允许使用“平面”数组结构。此外,由于您的数据源对每个值都有一个键,因此您必须使用 columns 选项指定它。因此,您的数据表代码将变为:

$('#example').dataTable( {
    "processing": true,
    "serverSide": true,
    "ajax": {
        "url": "http://WebSite_URL.com/data.php",
        "dataType": "jsonp",
        "jsonp":"mycallback",
        "dataSrc": ""
    },
    "columns": [
        {"data": "id"},
        {"data": "name"},
        {"data": "age"},
    ]
} );

这当然是假设你的 ajax 调用和 jsonp 回调都正确完成了。

【讨论】:

    【解决方案2】:

    这是一个 JSONP 调用,您提供了一个函数名称(此处为“mycallback”)。因此,服务器将发送数据,以便使用 JSON 数据调用您提供的函数。此处,mycallback([{"id" :"2","name":"Kelly","age":"12{"id":"3","name":"Robby","age":"12"}])。

    你需要做的是定义一个名为“mycallback”的函数,它有一个参数,你可以在那里做任何你想做的事情。

    例子:

      function mycallback(data){
                    var table = document.getElementById('example');
                    var tableHtml = '' // make the html here with this data (using a template engine)
                    table.innerHTML = tableHtml;
              }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      • 2015-02-02
      • 1970-01-01
      • 1970-01-01
      • 2013-02-19
      • 1970-01-01
      相关资源
      最近更新 更多