使用AngularJS发出请求

时间:2015-07-07 16:59:58

标签: javascript html angularjs request

我今天开始使用AngularJS,我尝试使用AngularJS向我的API发送帖子,但是当我点击我的按钮时,我什么也得不到,甚至没有错误500代码。
问题是什么根据我的要求?

API

@Controller
@RequestMapping("/veiculo")
public class VeiculoAPI {

    @RequestMapping(value = "/novo/{nome}", method = RequestMethod.POST)
    public void novoVeiculo(@Param("nome") String nome) {
        System.out.println("Veículo : " + nome);
    }

}

HTML

<!DOCTYPE html>
<html ng-app="oknok">
<script>
    function salvar($scope) {
        var nomeVeiculo = $scope.veiculo;
        $http.post("/veiculo/novo/", {"veiculo" : "nomeVeiculo"})
    .success(function (data, status, headers, config) {
            $scope.data = data;
        }).error(function (data, status, headers, config) {
            $scope.status = status;
        })
    }
</script>
<head lang="en">
    <meta charset="UTF-8"/>
    <title>OKNOK Admin</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.1/angular.min.js"></script>
</head>
<body ng-controller="formulario">

<center>
    <label>Veículo</label>
    <input type="text" ng-model="veiculo"/>
    <button ng-click="salvar()">Salvar</button>
</center>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

要使用angularJS向任何API发出HTTP请求,您需要执行以下步骤:

  1. 创建一个Controller文件&amp;其中的控制器
  2. 在控制器文件中创建角度模块
  3. 在控制器中创建HTTP请求
  4. 创建一个controller.js文件然后创建一个角度模块,见下面的代码:

      //Within your controller.js file 
        var myApp = angular.module('myApp', []);
        myApp.controller('myController', function($scope, $http){
    
     // Create a function within the scope of the module
     $scope.makeRequest = function(){
    
        // Simple POST request example (passing data) :
        $http.post("API url here", {
    
             //Enter Request data in here, this is the data you want to pass to the API
             msg:"Hello World",
             name: "John Smith",
             gender: "Male"
        }).
        success(function(data, status, headers, config) {
            // this callback will be called asynchronously
            // when the response is available
    
        }).
        error(function(data, status, headers, config) {
            // called asynchronously if an error occurs
            // or server returns response with an error status.
        });
    };
    });
    

    然后在您的HTML文件中调用该函数on-Click请参阅下面的代码:

    注意:不要忘记将您创建的控制器添加到HTML代码中。我通常将它添加到body标签

     <body ng-controller="myController">
        <button ng-click="makeRequest()">Make Request Button</button>
     </body>
    

    要发出GET请求,请参阅以下代码:

      // Simple GET request example :
      $http.get('/someUrl').
        success(function(data, status, headers, config) {
      // this callback will be called asynchronously
     // when the response is available
     }).
       error(function(data, status, headers, config) {
        // called asynchronously if an error occurs
       // or server returns response with an error status.
     });
    

    我希望这会有所帮助。