2

我正在尝试通过 jquery ajax 调用传递一个数组。但是,我需要在上面使用描述性索引,例如。项目 [“sku”] = 'abc';

如果我创建以下数组:

item[1] = "abc";
item[2] = "def";

并将它传递给下面的ajax调用,我在php端得到了一个正确的数组

$.ajax({
    type: "POST",
    url: "/ajax/add_to_cart.php",
    data: {items: item},
    success: function(msg){ }
}); 

但是,像这样创建数组

item["sku"] = "abc";
item["title"] = "product";

在 php 端什么也不产生

有什么技巧可以推动这样的阵列通过吗?我尝试过使用 jquery stringify 但这没有帮助

另外,我需要以类似的方式传递二维数组。这可能吗?

4

3 回答 3

2

您可以像这样构建和发送收集的产品数据:

var item = [{sku:"abc", title:"product1"}, {sku:"def", title:"product2"}, {sku:"ghi", title:"product3"}];

$.ajax({          
    type: "POST",
    url: "/ajax/add_to_cart.php",
    data: {items: JSON.stringify(item)},
    dataType: "json",
    success: function(msg){ }
});

json_decode() 将在 PHP 端帮助您:

<?php
    var_dump(json_decode($_REQUEST['items'], true));
?>
于 2012-05-02T21:31:20.000 回答
2

我假设您正在使用 [] 文字或 new Array() 创建一个 Array 实例。尽管您正在寻找的数据结构在 JavaScript 中称为对象,但在其他环境中它们也可以称为关联数组、哈希图或字典。要在 JavaScript 中创建和填充对象,您可以执行以下操作:

var item = {};
item["sku"] = "abc";
item["title"] = "product";
于 2012-05-02T21:32:13.217 回答
1

您将需要仔细查看 PHP 的json_encode()json_decode()函数:http ://php.net/manual/en/function.json-decode.php (整个库确实会有所帮助)以及 jQuery 的$.getJSON()$.post()函数:http: //api.jquery.com/jQuery.post/

<?php

$items_array = json_decode( $_REQUEST['items'], true );

foreach ( $items_array as $key=>$value ){
    // $key = 'sku', 'title', etc.
    // $value = 'abc', 'product', etc.
    // $value might include array( 'key'=>'value', 'key'=>'value' ) when multidimensional
}
于 2012-05-02T21:28:22.937 回答