javascript - Make requests with AngularJS -
i started angularjs today , trying send post api angularjs don't anything, not error 500 code when click in button.
what problem request?
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>
to make http requests api angularjs need following steps:
- create controller file & controller within it
- create angular module within controller file
- create http request within controller
create controller.js file create angular module see code below:
//within controller.js file var myapp = angular.module('myapp', []); myapp.controller('mycontroller', function($scope, $http){ // create function within scope of module $scope.makerequest = function(){ // simple post request example (passing data) : $http.post("api url here", { //enter request data in here, data want pass api msg:"hello world", name: "john smith", gender: "male" }). success(function(data, status, headers, config) { // callback called asynchronously // when response available }). error(function(data, status, headers, config) { // called asynchronously if error occurs // or server returns response error status. }); }; }); then within html file call function on-click see code below:
note: don't forget add controller created html code. add in body tag
<body ng-controller="mycontroller"> <button ng-click="makerequest()">make request button</button> </body> to make request see code below:
// simple request example : $http.get('/someurl'). success(function(data, status, headers, config) { // callback called asynchronously // when response available }). error(function(data, status, headers, config) { // called asynchronously if error occurs // or server returns response error status. }); i hope helps.
Comments
Post a Comment