php - 使用 AngularJS 将数组作为参数传递给 PHP Restful Api

标签 php angularjs arrays http get

在我的本地环境中,我使用 PHP7 并为 AngularJS 应用程序开发了一个 Restful API。我需要向 Api 发出一个获取请求并将一个数组作为参数传递,所以我做到了:

$http.get("/Api/MyUrl.php", {
    params: {
        "Names[]": ["Foo", "Bar"]
    }
})
.then(function(response){ //fires in success
    console.log(response.data);
}, function(response){ //fires in error
    console.log(response.statusText);         
});

在 MyUrl.php 文件中,我在屏幕上打印了这样的参数:

<?php
   print_r($_GET);
?> 

执行的时候,浏览器控制台打印出了我想象中的样子:

Array
(
    [Names] => Array
        (
            [0] => Foo
            [1] => Bar
        )

)

到这里就没有问题了。但是,当我在服务器上上传应用程序时,它只支持 5.6 PHP 版本(我不知道它是否相关,但我认为是这样),带有数组的参数是由 PHP 以另一种方式获取的,什么打印在控制台上的是:

Array
(
    [Names%5B%5D] => Bar
)

它将 [] 信号“理解”为其 HTML 代码(%5B 和 %5D),仅获取数组的最后一个元素并将其解释为公共(public)变量。

要像在本地环境中一样读取服务器中的参数,我需要做什么?

最佳答案

好问题。我建议你结帐this old issue在它读取的 angularjs 项目中:

There is no particular standard for how arrays should be serialized into query strings. Different back ends expect different formats. This current method (in 1.1.x) was chosen specifically because it allows the developer the most flexibility.

您将参数传递给 $http.get() 的方式似乎适用于 php7.0,因为 php7.0 可能足够聪明,可以推断正在传递括号。但事实是,您的 Angular 代码中的查询字符串未正确进行 URI 编码,因此它无法针对您的服务器。

有趣的是,类似的问题已被报道here which 的答案引用了具有相同行为的 jQuery 文档:

Because there is no universally agreed-upon specification for param strings, it is not possible to encode complex data structures using this method in a manner that works ideally across all languages supporting such input. Use JSON format as an alternative for encoding complex data instead.

解决方案是什么?

首先,您可以尝试 URI-encoding你的参数。

另一种解决方案是将您的查询作为 json 编码数据传递:

$http.get("/Api/MyUrl.php", {
    params: {
        "data": JSON.stringify({'names': {'Foo', 'Bar'}})
    }
})

json_decode($_GET['data']) 在后端访问您的参数。

最后,您可以利用 AngularJS 的 paramSerializer定义您自己的序列化程序并像以前一样传递您的参数。 在这种特殊情况下,paramSerializerJQLike 将很有用:

$http.get("/Api/MyUrl.php", {
    params: {
        "Names[]": ["Foo", "Bar"]
    }
    paramSerializer: '$httpParamSerializerJQLike'
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
})

关于php - 使用 AngularJS 将数组作为参数传递给 PHP Restful Api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42302419/

相关文章:

php - 带有连接和空白行的 mysqli 查询

javascript - 仅在 Angular 模板中生成一次随机 ID 号

javascript - AngularJS 中的路由错误

javascript - 为什么这些 AngularJS 应用程序不能一起运行?

java - 银行计划未按预期运作

java - 如何在java中创建一个元素数组?

php - 这是什么类型的字符编码?在 MySql 中存储它的最佳数据类型是什么?

php - Doctrine 查询语法错误

algorithm - 不定长数组

php - 使用 php 从 Joomla 文章中获取图像