令人驚訝的是,我發現這個主題幾乎沒有任何東西,但我認爲這是一個非常簡單的解決方案。在括號內打印javascript變量
問題描述:
我有填充有PHP變量JavaScript變量:
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需要一個合適的對象,而不是預期的我不得不重寫整個數據表工作的字符串() - 調用。感謝MueR讓我走上正軌。
基本上,我將打印的PHP變量轉換爲標準的JSON對象,並將其作爲JSON對象設置爲變量的其他選項進行了擴展。
我所做的一切則是:
var createdParams = $.extend({}, createdEncode, appendix);
該插頭的「附錄」 -JSON到createdEncode,因此呼叫現在的工作:
$('#postsCreatedData').dataTable(createdParams);
什麼的* *生成的JavaScript看起來像?這是給你錯誤的代碼。在嘗試修復產生它的代碼之前,找出你想要產生的東西! – Quentin
很難回答這個問題,因爲儘管你已經解釋了,但是我們根本不知道客戶端的輸出是什麼,而沒有親自看到它。您可以從客戶端查看網頁的源代碼,然後將JavaScript中顯示的內容完全添加到您的問題中,作爲PHP分析的代碼行的輸出:var createdEncode ='<?php echo createdEncode; ?>';' –
好吧,我用完整的字符串更新了我的問題:) – Karl