从jquery $ .ajax到angular $ http

from jquery $.ajax to angular $http

我有这个jQuery代码,可以很好地交叉起源:

1
2
3
4
5
6
7
8
9
10
11
12
13
jQuery.ajax({
    url:"http://example.appspot.com/rest/app",
    type:"POST",
    data: JSON.stringify({"foo":"bar"}),
    dataType:"json",
    contentType:"application/json; charset=utf-8",
    success: function (response) {
        console.log("success");
    },
    error: function (response) {
        console.log("failed");
    }
});

现在我想把它转换成Angular.js代码而没有任何成功:

1
2
3
4
5
6
7
8
9
10
11
12
13
$http({
    url:"http://example.appspot.com/rest/app",
    dataType:"json",
    method:"POST",
    data: JSON.stringify({"foo":"bar"}),
    headers: {
       "Content-Type":"application/json; charset=utf-8"
    }
}).success(function(response){
    $scope.response = response;
}).error(function(error){
    $scope.error = error;
});

任何帮助赞赏。


AngularJS调用$ http的方式如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
$http({
    url:"http://example.appspot.com/rest/app",
    method:"POST",
    data: {"foo":"bar"}
}).then(function successCallback(response) {
        // this callback will be called asynchronously
        // when the response is available
        $scope.data = response.data;
    }, function errorCallback(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        $scope.error = response.statusText;
});

或者使用快捷方法可以更简单地编写:

1
2
$http.post("http://example.appspot.com/rest/app", {"foo":"bar"})
.then(successCallback, errorCallback);

有很多事情需要注意:

  • AngularJS版本更简洁(特别是使用.post()方法)
  • AngularJS将负责将JS对象转换为JSON字符串并设置标题(可自定义)
  • 回调函数分别命名为successerror(另请注意每个回调的参数) - 在角度v1.5中不推荐使用
  • 改用then函数。
  • 有关then用法的更多信息,请点击此处

以上只是一个快速示例和一些指示,请务必查看AngularJS文档以获取更多信息:http://docs.angularjs.org/api/ng.$http


我们可以通过在AngularJs中使用http服务来实现ajax请求,这有助于从远程服务器读取/加载数据。

$ http服务方法如下所示,

1
2
3
4
5
6
7
 $http.get()
 $http.post()
 $http.delete()
 $http.head()
 $http.jsonp()
 $http.patch()
 $http.put()

其中一个例子:

1
2
3
4
5
6
7
    $http.get("sample.php")
        .success(function(response) {
            $scope.getting = response.data; // response.data is an array
    }).error(){

        // Error callback will trigger
    });

http://www.drtuts.com/ajax-requests-angularjs/


你可以用这个:

下载"angular-post-fix":"^ 0.1.0"

然后在声明角度模块时将"httpPostFix"添加到依赖项中。

参考:https://github.com/PabloDeGrote/angular-httppostfix


你可以使用$ .param来分配数据:

1
2
3
4
5
6
7
8
9
 $http({
  url:"http://example.appspot.com/rest/app",
  method:"POST",
  data: $.param({"foo":"bar"})
  }).success(function(data, status, headers, config) {
   $scope.data = data;
  }).error(function(data, status, headers, config) {
   $scope.status = status;
 });

看看这个:AngularJS + ASP.NET Web API跨域问题