1

我在 jquery 中有一个工作代码,我使用request.setRequestHeader("X-CSRF-Token", $.cookie('token'));. 我知道如何将表单数据转换为$scopeusing ng-model,但是如何将submit_this()下面的函数转换为角度兼容的函数?

jQuery代码:

$("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;   
}
4

1 回答 1

2

您可以使用 $http 服务来做到这一点。您最好创建自己的服务,演示代码:

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
               });
     };
});

这是角度 $http 文档。

于 2014-11-13T03:49:33.890 回答