从Dynatable加载远程JSON
更新:为了避免问题完全归结为相同的原始策略,我尝试在本地提供服务,其中所有资产都来自http://localhost:4000
使用Serve 。 它没有解决问题。 因此,由于相同的原始策略,编辑小提琴可能不起作用,但您可以在那里看到代码。
我正在尝试使用Dynatable加载外部JSON,跳过read / normalize步骤(从现有表生成JSON)。 这应该得到支持,但它对我不起作用。
这是我对JSFiddle的尝试 。 从文档中加载JSON(这对我来说似乎并不十分有用)工作正常,如小提琴中所见。 但是从URL中提取它根本不起作用。
这是我的JavaScript:
// getting JSON from the document works, but of what use is that? $(document).ready( function() { $('#local').dynatable({ dataset: { records: JSON.parse($('#music').text()) } }); // getting JSON from a remote source fails: $('#remote').dynatable({ dataset: { ajax: true, ajaxOnLoad: true, ajaxUrl: '//www.dynatable.com/dynatable-ajax.json', records: [] } }); });
…引用两个表,一个id为“local”,另一个id为“remote”,以及包含本地表数据的脚本:
Remote JSON: Failing
Some Attribute Some Other Attribute
Local JSON: Succeeding
Band Album
[ { "band": "The Police", "album": "Ghost In The Machine" },{ "band": "Supertramp", "album": "Breakfast In America" },{ "band": "Peter Tosh", "album": "Mama Africa" },{ "band": "The Police", "album": "Regatta d'Blanc" },{ "band": "The Police", "album": "Zenyatta Mondatta" },{ "band": "Supertramp", "album": "Crime of the Century" },{ "band": "Talking Heads", "album": "Remain in Light" },{ "band": "Talking Heads", "album": "Speaking in Tongues" } ]
远程无法工作的原因是因为在通过AJAX获取数据时,响应JSON必须包含一些元数据以及实际记录。
如果查看dynatable文档中的AJAX示例 ,可以单击“查看AJAX数据”以查看格式:
{ "records": [ { "someAttribute": "I am record one", "someOtherAttribute": "Fetched by AJAX" }, { "someAttribute": "I am record two", "someOtherAttribute": "Cuz it's awesome" }, { "someAttribute": "I am record three", "someOtherAttribute": "Yup, still AJAX" } ], "queryRecordCount": 3, "totalRecordCount": 3 }
您可以看到实际结果数组嵌套在响应JSON中的"records"
下,并且它还返回集合中总计记录的数量,以及当前集合中的记录数量。
dynatable需要这个元数据的原因是为了在表格底部进行分页和记录计数文本 。 由于您的服务器正在进行实际的查询,排序和分页(例如,通过数据库查询或其他服务器端处理),因此dynatable只能看到最终结果。 因此,dynatable永远不会知道:
-
集合中的总记录数量是多少
-
筛选/查询集(所有页面)中的记录数量与
-
过滤/查询的分页集(当前页面)中有多少条记录。
dynatable可以从返回的结果中推断出唯一的东西是(3)从上面开始,即在当前页面上过滤/查询的集合中有多少条记录。 因此,它需要从服务器返回的JSON告诉它(1),即totalRecordCount
,以及(2),即queryRecordCount
。
当然,如果你不想要所有这些,你可以关闭分页和记录计数文本,并告诉dynatable结果将位于服务器返回的JSON的根目录:
$('#remote').dynatable({ features: { paginate: false, recordCount: false }, dataset: { ajax: true, ajaxOnLoad: true, ajaxUrl: '//www.dynatable.com/dynatable-ajax.json', records: [] }, params: { records: '_root' } });