Angularjs $http POST请求空数组

23 浏览
0 Comments

Angularjs $http POST请求空数组

下面的$http请求执行成功,但是在另一端的PHP脚本接收到一个空的$_POST数组,而实际上应该接收到\'test\'和\'testval\'。有任何想法吗?

0
0 Comments

问题的原因是在发送POST请求时,请求体中的参数是一个空数组。

解决方法是在AngularJS的配置中设置$httpProvider的defaults.transformRequest属性。该属性是一个函数,用于对请求体进行转换。在这个例子中,使用了一个匿名函数,判断如果请求体参数是undefined,则直接返回该参数;否则,使用$.param()函数将参数转换为url-encoded格式。然后,通过设置$httpProvider.defaults.headers.post['Content-Type']属性,将请求的Content-Type设置为'application/x-www-form-urlencoded; charset=UTF-8'。

这样,在发送POST请求时,如果请求体参数是一个空数组,会被正确地转换为url-encoded格式。

0
0 Comments

问题原因:这是AngularJS中的一个常见问题。问题出现的原因是由于默认的content-type头部设置不正确,导致POST请求时发送的数组为空。

解决方法一:更改默认的content-type头部设置。可以使用以下代码来更改:

$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded; charset=UTF-8;";

这样做可以确保正确的content-type头部被发送。

解决方法二:使用XHR请求拦截器对有效载荷对象进行正确的序列化。可以使用以下代码来实现:

$httpProvider.interceptors.push(['$q', function($q) {
    return {
        request: function(config) {
            if (config.data && typeof config.data === 'object') {
                config.data = serialize(config.data);
            }
            return config || $q.when(config);
        }
    };
}]);

这样做可以确保有效载荷数据再次在$_POST数组中可用。更多关于XHR拦截器的信息,请参考链接:[XHR interceptor](http://blog.brunoscopelliti.com/xhr-interceptor-in-an-angularjs-web-app)。

解决方法三:保持默认的content-type头部设置,并在服务器端解析有效载荷。可以使用以下代码来实现:

if(stripos($_SERVER["CONTENT_TYPE"], "application/json") === 0) {
    $_POST = json_decode(file_get_contents("php://input"), true);
}

这样做可以解决服务器无法正确解析有效载荷的问题。

以上是解决AngularJS $http POST请求空数组的几种方法,根据具体情况选择适合的方法来解决该问题。

0
0 Comments

问题:AngularJS的$http POST请求发送空数组的问题出现的原因以及解决方法

原因:根据提供的代码和问题描述,问题可能出现在数据的格式和后端处理方式上。在给定的代码中,发送的数据是一个简单的字符串,后端使用$_POST来获取数据。然而,如果要发送一个空数组,需要将数据的格式更改为JSON对象,并使用$_POST来获取数据。

解决方法:修改代码中的数据格式和后端处理方式,使其能够正确发送和接收空数组。

修改后的代码如下:

$http({
    url: 'backend.php',
    method: "POST",
    data: { test: [] },
    headers: {'Content-Type': 'application/json'}
}).success(function (data, status, headers, config) {
    console.log(data);
}).error(function (data, status, headers, config) {});


通过以上修改,可以正确发送和接收空数组。

参考链接:

- [stackoverflow.com/questions/34480438](http://stackoverflow.com/questions/34480438)

- [docs.angularjs.org/api/ng/service/$http](https://docs.angularjs.org/api/ng/service/$http)

- [stackoverflow.com/questions/19254029](http://stackoverflow.com/questions/19254029)

- [corpus.hubwiz.com/2/angularjs/19254029.html](http://corpus.hubwiz.com/2/angularjs/19254029.html)

0