如何从AngularJS将数据发布到Zend控制器?

11 浏览
0 Comments

如何从AngularJS将数据发布到Zend控制器?

视图页面:\n

邮箱: 密码:

\nmain.js\n

function LoginCtrl($scope, $http) {
$scope.login = {};
$scope.submit = function(){
    $http({
        method: 'POST',
        url: '/login',
        data: $scope.login,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    }).
        success(function(response) {
            window.location.href = "/login";
        }).
        error(function(response) {
            $scope.codeStatus = response || "请求失败";
        });
}

\nLoginController:\n

if ($request->isPost()) {
            $data = json_decode(file_get_contents("php://input"));}

\n我需要从Angular表单中获取数据,将其传递给Zend控制器,并进行登录检查和提交表单。有人可以提供逐步解释吗?

0
0 Comments

问题的原因是angular发送的数据方式与php所期望的方式不同,具体来说是采用了json编码。当遇到这个问题时,请求是空的。解决方法可以参考以下的帖子:

AngularJs http post does not send data

根据这个帖子的回答,可以通过在angular的$http请求中设置请求头的Content-Type为application/x-www-form-urlencoded来解决问题。具体方法如下所示:

$http({
  method: 'POST',
  url: '/your/url',
  headers: {'Content-Type': 'application/x-www-form-urlencoded'},
  transformRequest: function(obj) {
    var str = [];
    for (var p in obj)
      str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
    return str.join("&");
  },
  data: {name: 'John', age: 30}
});

在Zend Controller中,可以通过使用getParams()方法来获取POST的数据。具体方法如下所示:

$request = $this->getRequest();
$postData = $request->getParams();

通过以上的解决方法,就可以实现从angular js向zend controller发送数据的功能了。

0
0 Comments

如何从AngularJS中的控制器将数据发送到Zend控制器?

问题原因:在AngularJS控制器中,将登录信息作为参数传递给$http.post()方法时,数据格式不正确。因此,Zend控制器无法正确接收和处理数据。

解决方法:更改main.js文件中的代码,确保正确的数据格式被发送到Zend控制器。

首先,修改AngularJS控制器的代码如下:

function LoginCtrl($scope, $http) {
    $scope.login = {email: "", password: ""};
    $scope.submit = function(){
        $http({
            method: 'POST',
            url: '/login',
            data: $.param($scope.login),
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        }).
        success(function(response) {
            window.location.href = "/login";
        }).
        error(function(response) {
            $scope.codeStatus = response || "Request failed";
        });
    }
}

然后,在Zend控制器的PHP文件中,通过$_POST数组访问email和password参数,如下所示:

$email = $_POST['email'];
$password = $_POST['password'];

通过以上修改,AngularJS控制器将正确格式的数据发送到Zend控制器,使其能够正确接收和处理数据。希望对您有所帮助。

0