问题:angularjs在处理程序内发布数据

时间:2014-06-04 13:19:17

标签: javascript ajax json angularjs

我遇到了我的$ http.post工作不正常的问题。每次我发帖子时,似乎根本就没有发送数据。

这是我的帖子:

  $http({
      method: 'POST',
      url: "http://localhost:8080/app/api/v0/user/?access_token=" + UtilService.accessToken,
      data: data
      }).success(function(data){
          console.debug(data);
      }).error(function(data){
          alert("error");
          console.debug(data);
  });

数据json:

var data = {
    "country": $scope.country,
    "firstname": $scope.firstname,
    "lastname": $scope.lastname,
    "username": $scope.username
}

我从html中的表单中获取数据。

到目前为止,我尝试添加带

的标题
headers: {'Content-Type': 'application/json'}

headers: {'Content-Type': 'application/x-www-form-urlencoded'}

在发送数据之前,我还尝试了JSON.Stringify(data)angular.toJSson(data)。 我甚至尝试过Make AngularJS $http service behave like jQuery.ajax()

的建议

但似乎没有任何效果。当我通过Postman发送帖子时,一切正常,我得到了预期的答案。当我通过$http.post()发送它时,我只得到一个空数据,最后我会在错误回调中结束。

我确信由于Postman测试,我构建的网址是正确的。我觉得问题来自我发送的数据对象。即使我发送一个非常简单的json,如:

{
"firstname": "asdf",
"lastname": "asdf"
}

我仍然收到一个空的数据对象。

我现在搜索了几个小时,我不知道这种不端行为来自哪里。我非常感谢任何建议!

编辑:问题似乎来自于我试图在$http.post内拨打promise.then(function(result){ /*where I call the $http.post()*/ })这一事实。

如果我在then()之外拨打电话,我会得到一个合适的答案。但我需要等待数据,直到我发送我的帖子。那么在then()内发送帖子的方法有什么问题?

编辑:哈希值是我需要等待的值

var deferred = $q.defer(); 

createPasswordHash(email, newPassword1,
                function (hash) {
                    deferred.resolve(hash);
                },
                function (current, total) {

                }
            );

            var promise = deferred.promise;

            promise.then(function (result) {
                var data = {
                     "country": $scope.country,
                     "firstname": $scope.firstname,
                     "lastname": $scope.lastname,
                     "username": $scope.username,
                     "hash": result
                }
                $http.post("http://localhost:8080/app/api/v0/user/?access_token=" + UtilService.accessToken, data).success(function (data) {
                    alert("success");
                }).error(function (data) {
                    alert("error");
                    console.debug(data);
                });
            });

当我在createPasswordHash方法中调用$http.post()时遇到了同样的问题。

0 个答案:

没有答案