通过 POST 从 AngularJS 发送“关联数组”

Sending an "associative array" via POST from AngularJS

本文关键字:关联 数组 关联数组 发送 POST AngularJS 通过      更新时间:2023-09-26

我有一个'过滤器'对象,比如

{
  name: 'text',
  value: 'xxx',
  field: 'firstname'
}

它表示字段的过滤器,并在我更改输入字段的值时更新。我尝试通过以下方式将其存储在数组中:

$scope.active_filters[filter.field] = filter;

这样我就知道我在哪个字段上得到了哪个过滤器。过滤应该在服务器端进行,所以我正在尝试将此数组发送到我的 API。

$http.post(url, $scope.active_filters)

正如我在 Chrome 中看到的那样,我有一个数组,其中包含所需的元素,但长度为 0

[status: Object]
length: 0
  status: Object
    field: "status"
    name: "text"
    value: "x"
    __proto__: Object
__proto__: Array[0]

但是该对象未在我的请求中发送。如果我通过$scope.active_filters.push(filter)添加对象,它将发送到服务器,但它的索引为 0 而不是我想要的值。

我怎样才能实现我的两个目标?我的数组中的命名索引并将数据发送到 api。

我在这里猜测,但你的代码是这样的:

var assoc_array = [];
assoc_array["foo"] = "bar";
assoc_array["ipsum"] = "lorem";

JavaScript 不像 PHP 那样知道关联数组。JavaScript 有对象,由于一切都是对象(甚至是数组),你可以得到这种情况。

不是设置数组中的元素,而是将属性分配给对象。这意味着神奇.length属性不会更新,因为数组仍然为空。

如果将代码更改为:

var assoc_array = {}; // <-- {} instead of []     
assoc_array["foo"] = "bar";
assoc_array["ipsum"] = "lorem";

您将获得一个对象(而不是数组),并且不会有.length属性。

这就是使用数组的方式

var indexed_array = [];
indexed_array[0] = "bar";
indexed_array[1] = "lorem";
indexed_array.length; // 2
indexed_array[100] = "foo";
indexed_array.length; // 101 - arrays are never sparse in JS, PHP will give 3
indexed_array[2]; // undefined