我有以下json编码的数组,我按如下方式传递给JQuery,当数组中有元素时,一切正常。但是,有时候数组可能是空的 根据用户选择,这就是我的脚本崩溃的地方:
PHP
$myleaderarray = [{"Week_count":"3","Userid":"102","Username":"gsd555","MedCondPrimary":"Diabetes"},{"Week_count":"0","Userid":"216","Username":"gsd3","MedCondPrimary":"Cardiac Respiratory"}]
$count = count($myleaderarray); //1
JQ
var myleaderarray = <?php echo $myleaderarray; ?>; // this passes the array as expected
console.log(myleaderarray.length); //2
这是我在json_encoded数组为空时在控制台中看到的
JQ
var myleaderarray = ;
"Unexpected token ';'"
我似乎无法在JQ中测试此错误,所以我必须在服务器端执行此操作,或者 我完全错过了什么吗?谢谢你的帮助。
答案 0 :(得分:0)
变化:
var myleaderarray = `<?php echo $myleaderarray; ?>;`
到
var myleaderarray = "<?php echo $myleaderarray ?>";
答案 1 :(得分:0)
$myleaderarray = ['{"Week_count":"3","Userid":"102","Username":"gsd555","MedCondPrimary":"Diabetes"}','{"Week_count":"0","Userid":"216","Username":"gsd3","MedCondPrimary":"Cardiac Respiratory"}'];
$count = count($myleaderarray); // is now two
JQ
var myleaderarray = <?php var_dump($myleaderarray); ?>; // this passes the array as expected
console.log(myleaderarray.length);