AngularJS - TypeError:string不是函数

时间:2014-04-24 04:17:26

标签: javascript spring angularjs spring-mvc

我有一个AngularJS控制器,它将表单数据传递给Spring控制器。 Spring控制器返回一个jsp页面作为它的响应。当我用GET方法直接调用spring控制器时,这很好用。当我通过提交按钮中的TypeError: string is not a function呼叫控制器时,我在Chrome控制台中获得ng-click

表格: -

<form name="empForm" ng-controller="insertEmpCtrl"   >
    Name: <input type="text" class="form-control" name="fname" ng-model="formData.fname"/></form>
    <input type="submit" value="Save" ng-click="insertEmp()" />
</form>

AngularJS控制器: -

empApp.controller('insertEmpCtrl',function($scope,$http){

        $scope.insertEmp = function(){
            $scope.formData = {};
            $http.post("http://localhost:8080/IdeaOne/addemp", $scope.formData, {
                withCredentials: true,
                headers: {'Content-Type': undefined},
                transformRequest: angular.identity
            }).success($scope.message = "employee added").error(console.log("error"));
        };
    });

Spring控制器: -

@RequestMapping(value="/addemp",method = {RequestMethod.POST, RequestMethod.GET})
public String addEmployee(ModelMap model) {
    String fname = model.get("fname").toString();
    String lname = model.get("lname").toString();
    String contactno = model.get("contacton").toString();
    EmployeeManager.insertEmployee(fname,lname,contactno);


    return "hello";
}

控制台中的错误: -

TypeError: string is not a function
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js:70:515
at m.promise.then.u (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js:97:280)
at m.promise.then.u (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js:97:280)
at https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js:98:417
at h.$get.h.$eval (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js:108:482)
at h.$get.h.$digest (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js:106:62)
at h.$get.h.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js:109:287)
at f (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js:71:247)
at F (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js:75:408)
at XMLHttpRequest.x.onreadystatechange (https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js:76:457) 

有人可以告诉我解决这个问题的方法吗?

1 个答案:

答案 0 :(得分:1)

我认为问题出在这里......

.success($scope.message = "employee added")

$scope.message已分配&#34;员工已添加&#34; (字符串),然后作为回调函数传递给success()。当Ajax调用完成时,它将作为函数调用,从而导致错误。

相反,将函数作为回调传递...

$http.post("http://localhost:8080/IdeaOne/addemp", $scope.formData, {
    withCredentials: true,
    headers: {'Content-Type': undefined},
    transformRequest: angular.identity
}).success(function () {
    $scope.message = "employee added";
}).error(function () {
    console.log("error");
});