如何从angularjs向服务器发送数据

时间:2015-09-08 09:57:48

标签: java ajax angularjs spring

我正在尝试使用$ http.post()将数据发送到服务器。我写了一些代码,但没有显示任何内容。我只想发送一个字符串变量并从java页面打印出来。

<body ng-controller="HelloCtrl">    
 <script type="text/javascript">
    var app=angular.module("MyApp",[]);
    app.controller("HelloCtrl", function($scope, $http) {   
        $scope.name="Subhajyoti";           
        $scope.showName= function(){
            $http.post('insertEntry',$scope.name)
            .success(function(data){
                alert(data);
            })
            .error(function(data){
                alert("Error");
            })
        }
    });
 </script>
</body>

这是我的java页面代码..

@Controller
public class Rules {
@RequestMapping(value="insertEntry", method=RequestMethod.POST)
public @ResponseBody String insertEntry(@RequestParam String name){
    String val=name;
    System.out.println(val);
    JSONObject json = new JSONObject();
    String message = "Success";

    json.put("message", message);
    return json.toString();
}

}

我正在与spring mvc交互angularjs。请帮我举个例子。我是新手。

2 个答案:

答案 0 :(得分:0)

尝试

@RequestMapping(value="/insertEntry")

并且

$http.post('/insertEntry')

选中一个tutorial

答案 1 :(得分:0)

你需要这个:

   <html>
<head>
     <script type="text/javascript">
        var app=angular.module("MyApp",[]);
        app.controller("HelloCtrl", function($scope, $http) {   
            $scope.name="Subhajyoti";           
               $http.post('/insertEntry', {name:$scope.name}).
          then(function(response) {
            // this callback will be called asynchronously
            // when the response is available
          }, function(response) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
          }); 
        });
     </script>
</head>
<body >  
 <div data-ng-app="MyApp"
        ng-controller="HelloCtrl">

    </body>
</html>

并修改您的Controller课程,如下所示:

@Controller
public class Rules {
@RequestMapping(value="insertEntry", method=RequestMethod.POST)
public @ResponseBody String insertEntry(@RequestBody String name){
    String val=name;
    System.out.println(val);
    JSONObject json = new JSONObject();
    String message = "Success";

    json.put("message", message);
    return "".toString();
  }
}