【问题标题】:Pass jQuery object array to PHP with JSON使用 JSON 将 jQuery 对象数组传递给 PHP
【发布时间】:2011-03-25 16:46:23
【问题描述】:

传递数组后,如何访问 PHP 中的“代码”和“类型”值?
顺便说一句,我正在使用“jquery-json”插件。没有任何插件有没有办法做到这一点?

jQuery:

$(function(){

    function product(code, type) {

        return {
            code: code,
            type: type
        }

    }

    var products = [];

    products.push(product("333", "Product one"), product("444", "Second product"));

    var jsonProducts = $.toJSON(products); 

    $.post(
        "php/process.php",
        {products: jsonProducts},
        function(data){
            $("#result").html(data);
        }
    );


});

PHP:

<?php 

$products = json_decode($_POST["products"], true);

foreach ($products as $product){
    echo $product;
}

?>

【问题讨论】:

    标签: php jquery arrays json


    【解决方案1】:

    您的每个数组偏移量都是一个基本对象。

    foreach ($products as $product)
    {
        echo $product->code;
        echo $product->type;
    }
    

    我建议您重新阅读 json_decode 上的示例,以更好地了解 PHP 如何将 JSON 转换为 PHP 类型

    【讨论】:

    • 是的,这是我第一次尝试的,但我得到了这个:“注意:尝试在...中获取非对象的属性”
    • 当我执行 print_r 时,我得到了正确的数组结构: Array ( [code] => 333 [type] => Product one ) Array ( [code] => 444 [type] => Second product )
    • 是的!这样可行!但是为什么关联数组不起作用呢?
    • 哦,我明白了!我没有在 json_decode 中使用“true”来让它工作。谢谢
    • @elclanrs,添加 true 作为第二个参数将 JSON 解码为关联数组而不是对象。正如你所发现的:)
    【解决方案2】:

    您应该可以在 foreach 循环中只执行 $product-&gt;code$product-&gt;type

    顺便说一句,如果你想打印一个数组结构来检查格式,你可以使用print_r

    【讨论】:

      猜你喜欢
      • 2014-06-12
      • 1970-01-01
      • 2012-01-26
      • 2020-07-12
      • 2012-04-12
      • 1970-01-01
      • 2011-11-13
      • 2016-07-11
      • 1970-01-01
      相关资源
      最近更新 更多