douyun3799 2014-07-22 05:26
浏览 54
已采纳

通过json将多维数组从php解析为Javascript

I am trying to send an array from php to javascript through ajax and am having some troubles.

My php array code looks something like this:

if($_REQUEST['action'] == 'miniCart'){
  foreach($_SESSION['cart']['items'] as $item){
    $message[$item['id']]['name'] = $item['name'];
    $message[$item['id']]['price'] = number_format($item['price'], 2, '.', '');
    $message[$item['id']]['qty'] = $item['count'];
  }
    $message = json_encode($message,true);
}

And this builds an array that looks something like this:

[2] =>
     [name] => "Product 1"
     [price] => "$15.00"
     [qty] => "2"
[1] =>
     [name] => "Product 2"
     [price] => "$15.00"
     [qty] => "3"

My JS code looks something like this:

var miniCart = function () {
    $(".tester").on("click", function(event) {
    var action = 'miniCart';
        $.ajax({
            type: "POST",
            url: "cart/cart.php",
            data:"action=" + action + "&ajax=true",
            success: function(string){
                var obj = jQuery.parseJSON(string);
                alert( obj.name);

        }});
    }); 
}

My Json that is sent from php to JS looks like this:

{“2”:{“name”:”Product 1”,”price”:”15.00”,”qty”:”3”},”1”:{“name”:”Product 2”,”Price”:”15.00”,”qty”:”3”}}

I understand that this wont work, if someone can help finish this so that I can construct another array on the JS side that would be most helpful. My problem is that I can't parse them out correctly. I have tried many variations of JSON parsing but I think the "2" in the beginning is throwing it off. The item ID will never always be changing depending upon the order.

Perhaps I'm trying to engineer this incorrectly. I ultimately want to use these variables to build a shopping cart table.

Please assist.

Thank you kindly.

  • 写回答

1条回答 默认 最新

  • dongpao2871 2014-07-22 06:03
    关注

    And this builds an array that looks something like this:

    You're actually building an associative array in PHP, not a 0-indexed array. It then gets converted into a JSON object (with item IDs as keys), not a JSON array.

    To get the name of the item with ID "2" in javascript:

    alert(obj["2"].name);
    

    You can iterate over the JSON object like this:

    for (var key in obj) {
        console.log("Item ID: " + key);
        console.log(obj[key]);
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误