du21064 2019-01-28 17:51
浏览 81
已采纳

将PHP数组插入带有键值的JavaScript变量中

First, sorry if my problem is duplicated but I really try a lot of things but with no result. Second, my problem is that after using "json_encode($php_array)" and insert it into a js variable the output is "[object Object]" and it is not the $php_array.

Using key with the array (Bad result)

<script type="text/javascript">
// Some functions here
<?php
    $php_array = array('name'=>'joe','10','cat');
    $js_array = json_encode($php_array);
    echo "var javascript_array = ". $js_array . ";
";
?>
alert(javascript_array); // Output is: [object Object]
</script

Without using key (Good result)

<script type="text/javascript">
// Some functions here
<?php
    $php_array = array('joe','10','cat');
    $js_array = json_encode($php_array);
    echo "var javascript_array = ". $js_array . ";
";
?>
alert(javascript_array); // Output is: abc,def,ghi
</script

I expect the output of [{"name":"joe","cat"}], but the output is [object Object]

  • 写回答

1条回答 默认 最新

  • doudi7570 2019-01-28 17:54
    关注

    This is because the javascript alert() function isn't very clever - it knows how to output arrays nicely, but with objects it just gives up and says "it's an object!".

    You can make a nice pretty respresentation of the object like this:

    const prettyOutput = JSON.stringify(javascript_array, null, 4); //use indentation of 4 spaces
    alert(prettyOutput);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#单片机#的问题:以ATMEGA128或相近型号单片机为控制器设计直流电机调速的闭环控制系统(相关搜索:设计报告|软件设计|流程图)
  • ¥15 打开软件提示错误:failed to get wglChoosePixelFormatARB
  • ¥30 电脑误删了手机的照片怎么恢复?
  • ¥15 (标签-python|关键词-char)
  • ¥15 python+selenium,在新增时弹出了一个输入框
  • ¥15 苹果验机结果的api接口哪里有??单次调用1毛钱及以下。
  • ¥20 学生成绩管理系统设计
  • ¥15 来一个cc穿盾脚本开发者
  • ¥15 CST2023安装报错
  • ¥15 使用diffusionbert生成文字 结果是PAD和UNK怎么办