【问题标题】:AngularJS 1.2.0 $http not preserving array elementsAngularJS 1.2.0 $http 不保留数组元素
【发布时间】:2013-11-15 16:01:20
【问题描述】:

我最近升级到 AngularJS 1.2.0,但传递数组时出现问题,会破坏网站。在示例 $http 请求中,我正在传递如下字段:

$http.get({
                url : 'users',
                data : {
                    fields : 'user_id, user_name',
                    conditions : {
                        customer_id : current_site_id
                    },
                    join : ['customer_users']
                }
            });

在 1.0.8 的最后一个稳定版本中,连接的 [] 被保留,因此在 php 端它显示为数组并且是可迭代的。在 1.2.0 中,数组被删除,参数由浏览器传递给服务器:

conditions:{"customer_id":"9a83a3db-673e-407f-9a0d-1f804c4dcd01"}
fields:user_id, user_name
join:customer_users //<---- THIS SHOULD BE AN ARRAY!

因为它不是一个可迭代的对象,所以它破坏了 php 方面。因此,除了将所有数组变量从 ['xyz'] 重命名为 {'0': 'xyz'} 以模仿数组行为(尽管不是最佳的)之外,我如何确保 angularJS 将值作为数组传递?

【问题讨论】:

    标签: javascript php angularjs


    【解决方案1】:

    我认为您的示例根本不应该工作。应该是这样的:

    $http({
        method: 'GET',
        url : 'users',
        params : {
            fields : 'user_id, user_name',
            conditions : {
                customer_id : current_site_id
            },
            join : ['customer_users']
        }
    });
    

    1.1.1 开始,Angular 就可以正确地解析 url。规范说,如果你有一个数组,它将被解析为?join=item1&amp;join=item2。如果数组只有一项,则为 ?join=item1

    另一方面,jQuery.param() 会像这样解析它:?join[]=item1&amp;join[]=item2 而且它 - 如果我是对的 - 将确保 $_GET['join'] 始终是一个数组。

    总而言之,试试'join[]' : ['customer_users']。它可能会起作用。

    【讨论】:

    • 一种可能的解决方案,但该解决方案还要求我检查我制作的每个 $http 并对其进行修改。是可行的,但不是最优的。
    • 嗯,你可以随时拦截请求。 (docs.angularjs.org/api/ng.$http#description_interceptors) 在请求拦截器中,您将拥有一个 config.params。随意变换。
    • 谢谢!这是我可以写的更好的解决方案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 2012-08-02
    • 2016-08-13
    • 1970-01-01
    相关资源
    最近更新 更多