简体   繁体   English

将空的json_encode数组传递给JQuery

[英]Passing empty json_encode array to JQuery

I have the following json encoded array which I pass to JQuery as follows, and everything works fine when when there are elements in the array. 我有以下json编码的数组,我将其传递给JQuery,如下所示,当数组中有元素时,一切工作正常。 However, there are times when the array might be empty depending upon a users selections, and that is where my script breaks down: 但是,根据用户的选择,有时数组可能为空,这就是我的脚本崩溃的地方:

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

This is what I see in the console when the json_encoded array is empty 这是当json_encoded数组为空时在控制台中看到的内容

JQ
var myleaderarray = ;
"Unexpected token ';'"

I can't seem to test for this error in JQ so must I do this on the server-side, or am I completely missing something? 我似乎无法在JQ中测试此错误,因此必须在服务器端执行此操作,还是我完全丢失了某些内容? Thanks for the help. 谢谢您的帮助。

change: 更改:

var myleaderarray = `<?php echo $myleaderarray; ?>;` 

to

var myleaderarray = "<?php echo $myleaderarray ?>"; 
$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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM