angular.js $ http.post不工作​​ - 没有错误

时间:2013-04-30 11:58:33

标签: angularjs

我正在尝试使用$ http提交新评论。你可能从标题中猜到了它:它不起作用。我尝试了岸版和长版,都失败了。没有控制台错误。

这是我的代码:

$scope.comment = {};
$scope.comment["comment"] = message; // message defined somewhere else

$http.post('/api/items/'+$scope.item.id+'/comments', $scope.comment)
    .success(function(data, status, headers, config) {
         // this isn't happening:
         console.debug("saved comment", $scope.comment);
    })
    .error(function(data, status, headers, config) {
         // this isn't happening:
         console.debug("saved comment", $scope.comment);
    })
}

任何人都知道如何使这项工作?谢谢!

更新:

我现在正在将它作为Jquery ajax调用,这工作正常。尽管如此,让它与角度一起工作会很好。这是我的JQuery代码:

            var request = $.ajax({
                url: '/api/items/'+$scope.item.id+'/comments',
                type: "POST",
                data: JSON.stringify($scope.comment),
                contentType: 'application/json; charset=utf-8',
                dataType: "json"
            });

            request.done(function(msg) {
                console.debug("saved comment", $scope.comment);
            });

            request.fail(function(jqXHR, textStatus) {
                alert( "Request failed: " + textStatus );
            });

如果有人有任何想法如何对此进行角度化请告诉我,以正确的方式做到这一点会很好....

10 个答案:

答案 0 :(得分:7)

您在提出请求之前是否尝试过专门设置Content-Type?

我遇到了同样的问题,并设置了Content-Type修复它。

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

答案 1 :(得分:5)

也许这会对你有所帮助。我在调用时遇到了类似的问题:AngularJS $http not firing get call

我用解决方案解决了这个问题,在https://github.com/angular/angular.js/issues/2794#issuecomment-18807158找到了,所以我用$ scope包装了我的调用函数。$ apply。

$scope.$apply(function() {
                console.log('Klic na ID ' + data.context.id);
                $scope.commonController.getData('orgunit/' + data.context.id + '?jsonDepth=3')
                    .success(function(workpositionData,status,headers,config) {
                        console.log('Klic na ID ' + data.context.id + ' OK');
                        $scope.workPositions = workpositionData.workPositions;
                    }).error(function(data,status,headers,config) {
                        commonController.error('Pri branju delovnih mest je prišlo do napake: '+data.description);
                    });
            });

答案 2 :(得分:3)

我想,你只是忘了一些残忍的“)” 尝试

$http.post('/api/ideas/'+$scope.item.id+'/comments', $scope.comment)
   .success(function(data, status, headers, config) {
     // this isn't happening:
     console.debug("saved comment", $scope.comment);
   })  //<-- damn ")"
   .error(function(data, status, headers, config) {
     // this isn't happening:
     console.debug("saved comment", $scope.comment);
   }) //<--- damn ")"
 }

我还没有测试过,但我打赌,这是错误 问候

答案 3 :(得分:1)

如果您使用的是角度1.1.4+,请检查此帖子https://github.com/angular/angular.js/issues/2431

基本上如果你在Angular上下文之外调用$ http,你需要在$ scope中包装$ http回调。$ apply。有关详细信息,请查看https://github.com/angular/angular.js/issues/2794#issuecomment-18807158

答案 4 :(得分:0)

您需要使用$ http对象初始化控制器。您希望使用的其他Angular服务也是如此。

E.g:

function myCtrl($scope, $http) {
  // controller code
}

答案 5 :(得分:0)

你可以试试。

Angular js post call:

$http({
        url:'/api/ideas/'+$scope.item.id+'/comments', $scope.comment,
        method : 'POST'
    }).success(function(data, status, headers, config){
    }).error(function(data, status, headers, config){
    });

休息控制器:

@RequestMapping
    (value = "/api/ideas/{item_id}/comments/{comment}", method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    public void updateComments(@PathVariable String item_id,@PathVariable String comment) {
        }

答案 6 :(得分:0)

我正在努力解决同样的问题。我解决它的方法是使用.then() 并将成功和错误回调注册为参数。在你的情况下:

$http.post('/api/items/'+$scope.item.id+'/comments', $scope.comment)
  .then(
    // success callback
    function(response) {
      console.debug("success - saved comment", $scope.comment);
    },
    // error callback
    function(response) {
      console.debug("error - saved comment", $scope.comment);
   }
);

答案 7 :(得分:0)

//set arg
var arg = { name: $scope.name,
           tel: $scope.tel} 
// config 
var req = {
                method: 'POST',
                url: '/pServices/sellers/addNew',
                headers: {'Content-Type': 'application/json'},
                data: arg
            }
//POST data to server 
$http(req).then(function(data, status, headers, config){
                if(data['data']['status'])
                 console.log('success') ;

            }, function(data, status, headers, config){
                 console.log(data['data']['message']) 
            });

答案 8 :(得分:-1)

$http.post('/api/ideas/'+$scope.item.id+'/comments', $scope.comment).success(function(data, status, headers, config) {}).error(function(data, status, headers, config) {});

答案 9 :(得分:-1)

angular.module('RestService', [

]).factory('$RestService', [
    '$http', 'ApiUrl',
    function ($http, ApiUrl) {
        return {          
            Functioname: function (request) {
                var Requesturl = ApiUrl + "/Functionname";//www.test.com/getuserdata
                return this.Post(Requesturl, request);//request :parameter which you want to pass in post request
            },
            Post: function (ResultUrl, RequestParameterData) {
                var PostResponse = $http({
                    url: ResultUrl,
                    method: "POST",
                    dataType: "",
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
                    data: RequestParameterData
                });
                return PostResponse;
            },
            Get: function (ResultUrl, RequestParameterData) {
                var PostResponse = $http({
                    url: ResultUrl,
                    method: "GET",
                    dataType: "",
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' },
                    data: RequestParameterData
                });
                return PostResponse;
            }

        };
    }


]);