如何在Angular上使用Ajax

时间:2015-07-17 08:15:06

标签: javascript jquery ajax angularjs

我想在服务器上传文件并有进度条。我使用ajax上传。现在,我想将它们转换为angularjs。如何在angularjs上使用ajax。我正在研究ngularjs。拜托,帮助我。谢谢 HTML:

<form action="uploadFile" method="post" enctype="multipart/form-data">
        <input type="file" name="file" multiple><br>
        <input type="submit" value="Upload File to Server">
    </form>

    <div class="progress">
        <div class="bar"></div >
        <div class="percent">0%</div >
    </div>

    <div id="status"></div>

和js文件:

<script>
(function() {

var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');

$('form').ajaxForm({
    beforeSend: function() {
        status.empty();
        var percentVal = '0%';
        bar.width(percentVal)
        percent.html(percentVal);
    },
    uploadProgress: function(event, position, total, percentComplete) {
        var percentVal = percentComplete + '%';
        bar.width(percentVal)
        percent.html(percentVal);
        //console.log(percentVal, position, total);
    },
    success: function(xhr) {
        var percentVal = '100%';
        bar.width(percentVal)
        percent.html(percentVal);

    },
    complete: function(xhr) {
        status.html(xhr.responseText);
    }
}); 

})();       
</script>

2 个答案:

答案 0 :(得分:1)

使用$http

该链接的示例:

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

至于显示进度,这个插件看起来很有希望:Angular Loading Bar

即使只是包含它也会有效。

angular.module('myApp', ['angular-loading-bar'])

答案 1 :(得分:0)

dataService.DrivingScoreSendOffers=function(offers,callback){
         $.ajax({
            url:url,
            type: "POST/GET",
            cache:false,
            data:{
                "offers":offers,
            },
            success: function (data,textStatus,xhr) {
                callback(data);
            },
            error: function (xhr,exception) {
                 console.log(xhr);
                 console.log(exception);
            },
        });
        };

在APP / Dashboard中调用ajax的简单方法,在此dataService中就像angularjs中与服务器交互的服务(遵循MVC架构)。