简体   繁体   中英

Post request in an AngularJs single page application

I am building a single page application in Spring MVC and AngularJS. I have a header-footer-sidebar and an ng-view section where all the pages are loaded by Ajax with a routeProvider. The thing is that the routeProvider is only working with GET requests which means I cannot pass any parameters. ( I don't want to pass all the form data in the url ) I want to submit a form using Ajax POST request and in the same time change the ng-view content. Is this possible using Angular routeProvider?

The solution I have thought so far is to post the form data, receive a success message and then change the hash of the url in order to trigger a new request to the server for the new page. This solution though, has the drawback of performing 2 requests to the server while I want to perform only one.

Thank you

First of all you have to realize that routeProviders are there to change routes insider your application, not to pass data to server. use a service or a factory to pass data to the server, and return your response page from there. here is a simple example,

form:-

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

routing:-

myApp.config(function($routeProvider){
$routeProvider
    .when('/',{
        templateUrl : '/your/project/root.html',
        controller : 'controler1'
    })
    .when('/page',{
        templateUrl : '/your/project/page.html',
        controller : 'controler2'
    });
});

factory:-

myApp.factory('factoryname', function(){
return{
    insertData: function($scope,$http){
        var json_data = JSON.stringify($scope.formData);


        $http.post(url, json_data, {
            withCredentials: true,
            headers: {'Content-Type': 'application/json'},
            transformRequest: angular.identity
        }).success(function(){
            console.log("done");
        }).error(function(){
            console.log("error");
        });
    }
}
});

controller:-

myApp.controller('controller1',['$scope','$http','$rootScope','factoryname',function($scope,$http,$rootScope,factoryname){

$scope.insertEmp = function(){

    $scope.formFactory = factoryname.insertData($scope,$http);

};
}]);

spring controller:-

@RequestMapping(value="/aurlPattern",method = RequestMethod.POST)
public String insertmethod(@RequestBody  FormModelObject FormModelObject) {

    //do something


    return "responsePage";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM