AngularJS $http post后台无法接受参数问题

默认情况下,jQuery传输数据使用Content-Type: x-www-form-urlencodedand和类似于”name=zhangsan&age=18″的序列,然而AngularJS,传输数据使用Content-Type: application/json和{ “name”: “zhangsan”, “age”: “18” }这样的json序列。
所以,他们的请求方式看起来一样,但其实不然。jquery显得更加人性化。
解决方案:

1.将http替换成jquery方式 (不推荐)
2.第二种方式:修改PHP文件的方式
3.修改当前请求:代码如下

<script>
    var app = angular.module("myapp", []);
    app.config(function ($httpProvider) {
        $httpProvider.defaults.transformRequest = function (obj) {
            var str = [];
            for (var p in obj) {
                str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
            }
            return str.join("&");
        };
        $httpProvider.defaults.headers.post = {
            'Content-Type': 'application/x-www-form-urlencoded'
        }
    });
    app.controller("ctrl", ["$scope", "$http", function (scope, http) {
        http({
            method: 'POST',
            url: 'http://localhost/web007/data.php',
            data: {
                "username": "iwen"
            },
        }).success(function (data, header, config, status) {
            console.log(data);
//                scope.msg = data.list;
        }).error(function (data, header, config, status) {
        });
    }])
</script>

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注