weixin_33724059 2013-02-26 21:06 采纳率: 0%
浏览 43

遍历JSON数组

I have a JSON array that I'm passing to PHP. Eventually I'll be passing and receiving alot more from my PHP file but for the moment this is it. Right now it's recieving 1 array and sending back that same array, no problem. I can loop through the data in Javascript but how do I loop through the array I pass to my PHP file? I get errors with foreach and a for loop didn't seem to help any. Suggestions?

Javascript

var fullName = ["John Doe", "Jane Doe"];

$(window).load(function(){
    getList();
});

function getList(){
    $.getJSON(
        "names.php",
        {names : JSON.stringify(fullName)},
        function(data) 
        {
            for(var i = 0; i < data.test.length; i++)
            {
                window.alert(data.test[i]);
            }
        }
      );
}

PHP

<?php
    $names=json_decode($_REQUEST['names']);

foreach($names as $name)
{
    echo $name;
}

    $data['test'] = $names;
    echo json_encode($data);

The foreach errors out on the foreach line telling me "Warning: Invalid argument supplied for foreach()"

  • 写回答

6条回答 默认 最新

  • local-host 2013-02-26 22:03
    关注

    There seems to be something strange going on when using:

    {names : JSON.stringify(fullName)}
    

    As you are sending key - value pairs using GET or POST, you probably need to encode the value correctly.

    You could do that using:

    {names : encodeURIComponent(JSON.stringify(fullName))}
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 UE5#if WITH_EDITOR导致打包的功能不可用
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?
  • ¥15 电磁场的matlab仿真
  • ¥15 mars2d在vue3中的引入问题
  • ¥50 h5唤醒支付宝并跳转至向小荷包转账界面
  • ¥15 算法题:数的划分,用记忆化DFS做WA求调
  • ¥15 chatglm-6b应用到django项目中,模型加载失败