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 vika文档如何与obsidian同步
  • ¥15 华为手机相册里面的照片能够替换成自己想要的照片吗?
  • ¥15 陆空双模式无人机飞控设置
  • ¥15 sentaurus lithography
  • ¥100 求抖音ck号 或者提ck教程
  • ¥15 关于#linux#的问题:子进程1等待子进程A、B退出后退出(语言-c语言)
  • ¥20 web页面如何打开Outlook 365的全球离线通讯簿功能
  • ¥15 io.jsonwebtoken.security.Keys
  • ¥15 急,ubuntu安装后no caching mode page found等
  • ¥15 联想交换机NE2580O/NE1064TO安装SONIC