How do I execute an ajax post with request header in Angular

余生颓废 提交于 2019-12-25 01:24:02

问题


I am having a working code in jquery, where I post data from form with a token using request.setRequestHeader("X-CSRF-Token", $.cookie('token'));. I know how to get the form data into a $scope using ng-model, but how do I convert the submit_this() function below to an angular compatible function?

The Jquery Code:

$("body").on("click", "#login", function() {

        var url = "http://localhost/lab/theapp/api/user/login.json";    
        var name = $('#user').val();

        var pass = $('#pass').val();

        var data = 'username=' + encodeURIComponent(name) + '&password=' + encodeURIComponent(pass);
        var type = "post";

        submit_this(type,data,url);

    }); 


    //the function that need to be re-written for AngularJs   
    function submit_this(type,data,url) {
            try {   

                $.ajax({
                        url: url,
                        type: type,
                        data: data,
                        dataType: 'json',
                        beforeSend: function (request) {
                        request.setRequestHeader("X-CSRF-Token", $.cookie('token'));
                        },
                        error: function(XMLHttpRequest, textStatus, errorThrown) {

                        },
                        success: function (data) {
                            if (data.sessid){   
                                var sessid = data.sessid;
                                var session_name = data.session_name;
                                var token = data.token;
                                jQuery.cookie("token", token);
                            }
                            console.log(data);
                        }
                });
            }   
        catch (error) { console.log(error) }
        return false;   
}

回答1:


You can use $http service to do that. You'd better create you own service, Demo code:

var demoApp = angular.module("DemoApp");
demoApp.controller("yourcontroller", function($scope, yourService){
    yourService.postData("http://your/url", {"X-CSRF-Token": $scope.token})
        .success(function(data){
            //handle success response here
        }).error(function(error){
            //handle error response here 
        });                                  
});
demoApp.service("yourService", function($http){
    this.postData = function(url, _headers){
        return $http({
                  method: "POST", 
                  url: url,
                  headers: _headers
               });
     };
});

Here is angular $http document.



来源:https://stackoverflow.com/questions/26900545/how-do-i-execute-an-ajax-post-with-request-header-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!