weixin_33724059 2015-09-19 02:07 采纳率: 0%
浏览 91

用ajax获取一个json数组

I want to get an array that I used with Ajax. I already used this method with an other page and this time it doesn't work, so I don't see where is the problem.

I have an array :

var array_downloads = <?php echo json_encode($array_downloads);?>;

This array isn't empty, when I do a console.log I get the content, the list of the elements.

After that, I make my Ajax request like that :

$.post("pack.php", {arr:array_downloads}, function(data) { 
...
},'json');

So I send my array to the file .php.

Finally I want to get the array with this :

$array_downloads = $_POST["arr"];

And when I try to echo it (and I don't forget the json_encode()), I get null. I don't understand why. Help please !

  • 写回答

1条回答 默认 最新

  • perhaps? 2015-09-19 02:25
    关注

    I tries with the same code and it works as it is suppose to:

    The only code I changed is wrapped json_encode output in quotes so that javascript will consider it as a string.

    main.php

    <?php $array_downloads = [1, 2, 3, 4, 5]; ?>
    <script>
        var array_downloads = '<?php echo json_encode($array_downloads);?>';
        $.post("pack.php", {arr: array_downloads}, function (data) {
            console.log(data);
        }, 'json');
    </script>
    

    pack.php

    <?php
    var_dump(json_decode($_REQUEST['arr'],true));
    ?>
    

    Output in pack.php

    array (size=5)
      0 => int 1
      1 => int 2
      2 => int 3
      3 => int 4
      4 => int 5
    
    评论

报告相同问题?

悬赏问题

  • ¥66 关于川崎机器人调速问题
  • ¥15 winFrom界面无法打开
  • ¥15 crossover21 ARM64版本安装软件问题
  • ¥15 mymetaobjecthandler没有进入
  • ¥15 mmo能不能做客户端怪物
  • ¥15 osm下载到arcgis出错
  • ¥15 Dell g15 每次打开eiq portal后3分钟内自动退出
  • ¥200 使用python编写程序,采用socket方式获取网页实时刷新的数据,能定时print()出来就行。
  • ¥15 matlab如何根据图片中的公式绘制e和v的曲线图
  • ¥15 我想用Python(Django)+Vue搭建一个用户登录界面,但是在运行npm run serve时报错了如何解决?