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 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算