Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/74.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数组获取数据_Javascript_Jquery_Json_Jsonp - Fatal编程技术网

Javascript 从表中的JSON数组获取数据

Javascript 从表中的JSON数组获取数据,javascript,jquery,json,jsonp,Javascript,Jquery,Json,Jsonp,如果网站提供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="t

如果网站提供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>

$(文档).ready(函数(){
$('#示例')。数据表({
“处理”:对,
“服务器端”:正确,
“ajax”:{
“url”:”http://WebSite_URL.com/data.php",
“数据类型”:“jsonp”,
“jsonp”:“mycallback”
}
} );
} );
身份证件
名称
年龄

这是一个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;
          }

默认情况下,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"}]
现在,dataTables允许使用“平面”数组结构,方法是将
ajax
数组中的
dataSrc
选项作为空白值。此外,由于数据源中的每个值都有一个键,因此您必须指定使用
columns
选项。因此,dataTables代码将变为:

$('#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回调都正确完成。

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