AngularJS $http与jQuery $.ajax对比

15

我可以像在 jQuery 的 $.ajax 中那样,在 Angularjs $http 中设置 context 吗?

define([
    'app'
], function(app) {

    app.controller("controller1", function($scope, $route, $http) {

        return $http({
            method: 'GET',
            url: 'server.php'
        }).then(function(response) {
            $scope.contacts = response.data;
        });
    });
});

此外,在jQuery的$.ajax中有更多回调函数,例如.done.promise,我可以使用它们来操作context,像下面这样,我想知道在Angularjs中是否也能做到同样的事情?

$.ajax({
    type:       "GET",
    dataType:   "HTML",
    url:        'server.php',
    context:    $("#container"),
    async:      true,
    beforeSend: function() {

        $(this).html('loading...');
    },
    success: function (returndata, status, jqxhr) {
        $(this).html(returndata).hide().fadeIn();
    },
    }).fail(function() { 
        alert("error"); 
    }).done(function(returndata) {
    },
    .always(function() { 
        alert("complete"); 
    }
});
2个回答

24

两者是相同的

$http 是从 angular.js 脚本引用的

$.ajax 是从 jquery 脚本引用的

  • 而 $http 不支持 async:false

  • $.ajax 支持 async:false

您可以通过以下方式使用 angular.js 来实现

$http.get('server.php').success(function(response) {
            $scope.contacts = response.data;
        }).error(function(error)
    {
//some code    
});

但是angular.js不支持async: true

如果您需要停止异步回调,则必须使用$.ajax方法。

更多详细信息,请参见此讨论:从jquery $.ajax 到 angular $http

编辑:

如何在angular js中实现显示隐藏

<div ng-show="IsShow">xx</div>



  $http.get('server.php').success(function(response) {
                $scope.contacts = response.data;
                $scope.IsShow=true;
                $scope.$apply();
            }).error(function(error)
        {
           $scope.IsShow=false; 
           $scope.$apply(); 
    });

谢谢。我可以知道 ** 是用来做什么的吗? - Run
@lauthiamkok ** 什么都不是。它只是一个非常粗的行标记。$scope.$apply() 意味着 $scope.IsShow=true 应用于 HTML。但这可能并不需要。 - Ramesh Rajendran
谢谢。我觉得 jQuery 方法更简单、更直接,你不觉得吗? - Run
2
@lauthiamkok,没错,你可以使用jQuery来实现。那么为什么要使用Angular.js呢?你可以使用jQuery或Angular.js来完成它。两者都很好,但是Angular.js比jQuery更快地进行绑定。祝编码愉快 :) - Ramesh Rajendran
您能够稍微改善一下您回答中的英文语法吗?这样会更易于理解。 - psp

3

只需在您传递给 promise.then 的函数上使用 Function.bind() 来保持您想要的上下文。例如:

return $http({
    method: 'GET', 
    url:'server.php'
}).then(function(response) {
    $scope.contacts = response.data;
}.bind(this));

然而,我注意到你的回调函数都在操作元素——这些元素在Angular中是不必要的。你是否有特定的目标需要使用回调函数,但又不能实现?


谢谢Jeff。我只需要像在$.ajax中做两件事情 - 1.`beforeSend: function() { $(this).html('loading...'); }` 和 2 - `success: function (returndata, status, jqxhr) { $(this).hide().fadeIn(); }`。 - Run
所以...是的,你应该使用请求和响应拦截器,并根据挂起的HTTP请求数量来显示/隐藏它。 - Jeff Hubbard

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接