令人惊讶的是,我发现这个主题几乎没有,但我认为这是一个非常简单的解决方案。
问题描述:
我有一个Javascript变量,它填充了一个PHP变量:
var createdEncode = '<?php echo $createdEncode; ?>';
PHP包含一个JSON字符串,但没有开始和结束的花括号。我检查了分隔符问题但是我觉得这个字符串很好,亲眼看看:
var createdEncode = '"sEcho":1,"iTotalRecords":15,"iTotalDisplayRecords":11,"aaData":[["1","Suche Kurier","","dauerhaft, immer","","","ein geschenk","3","test dauerhaft","0","1","1","",""],["4","Suche Hilfe","1","bis 09.01.2014, sdfkdsjf","","","Du gibst: 9\u20ac","1","Auch gibt es niemanden, der den Schmerz an sich liebt, sucht ...","1","1","0","",""],["5","Suche Kurier","","bis 15.01.2014, jklkl","","","Du gibst: 8\u20ac","1","jllk","1","1","0","",""],["7","Suche Kurier","","bis 20.01.2014, jkljkl","","","Du gibst: 8\u20ac","1","nm,.","0","1","0","",""],["8","Suche Hilfe","1","am 25.01.2014 um 08:45 Uhr","","","Du gibst: 8\u20ac\/h","2","dsdf","0","1","0","",""],["9","Biete Kurier","","bis 08.01.2014, swrslkjk","","","kljkjl","3","Auto Kompaktklasse, H\u00e4lfte des Kofferraums freier Platz","1","1","0","2","4"],["10","Biete Hilfe","1","am 26.01.2014 um 12:45 Uhr","","","Du bekommst: 6\u20ac","1","sdsdfs","0","1","0","",""],["11","Suche Kurier","","bis 23.01.2014, sfui","","","Du gibst: 7\u20ac","1","jlkkjl","0","1","0","",""],["12","Suche Hilfe","1","am 15.01.2014 um 13:00 Uhr","","","Du gibst: 8\u20ac\/h","2","sdfkl","1","1","0","",""],["13","Biete Kurier","","bis 29.01.2014, erert","","","Du bekommst: 4\u20ac\/h","2","Zu Fu\u00df, Dreiviertel des Kofferraums freier Platz","0","1","0","0","5"],["14","Biete Hilfe","1","dauerhaft, dfgdf","","","Du bekommst: 3\u20ac\/h","2","xfsfds\u00f6k","0","1","0","",""]],"oLanguage":{"sUrl":"language\/dataTables.german.txt"}';
后来我得到了一些JS说:
$('#postsCreatedData').dataTable({
createdEncode,
"bAutoWidth": false,
"aoColumnDefs":[
{"aTargets .... stuff ...
我的问题是“createdEncode”什么也没做,控制台抛出Uncaught SyntaxError: Unexpected token ,
。 Meant是“createdEncode”之后的逗号。
我的方法:
我试过了
document.write(createdEncode);
它会抛出unexpected token .
。
还尝试了+ createdEncode +
。同样的事情,意外+ ...
我真的不知道该怎么做。你能为我提供一个解决方案,将该变量的内容打印到该数据表吗?
非常感谢。
解决方案:
由于Javascript需要一个合适的对象而不是一个字符串才能按预期工作,我必须重写完整的datatable() - 调用。感谢MueR让我走上正轨。
基本上我将打印的PHP变量转换为标准的JSON对象,并将其与我设置为变量的其他选项一起扩展为JSON对象。
我所做的就是:
var createdParams = $.extend({}, createdEncode, appendix);
将“附录”-JSON插入createdEncode,因此调用现在适用于:
$('#postsCreatedData').dataTable(createdParams);
答案 0 :(得分:1)
你的问题是你在那个对象中放了一个字符串(没有键),这是无效的。 您生成的javascript是
{
"a string without index, which is illegal",
"bAutoWidth": false,
"aoColumnDefs":[]
}
要正确地执行此操作,您需要让PHP也包括括号,而不是周围的单引号,因此它是一个实际的对象。然后,您必须将createdEncode
与包含bAutoWidth
等的其他对象合并。
你可以试试这个(假设你让PHP输出一个真正的javascript对象)
var dataTableParams = $.extend({}, createdEncode, {"bAutoWidth": false, .. other things ..});