从 jquery $.ajax 到 angular $http [英] from jquery $.ajax to angular $http

查看:26
本文介绍了从 jquery $.ajax 到 angular $http的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段 jQuery 代码可以很好地跨原点工作:

I have this piece of jQuery code that works fine cross origin:

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 代码,但没有成功:

Now I'm tring to convert this to Angular.js code without any success:

$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 的方式如下:

The AngularJS way of calling $http would look like:

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

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

or could be written even simpler using shortcut methods:

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

有很多事情需要注意:

  • AngularJS 版本更简洁(尤其是使用 .post() 方法)
  • AngularJS 将负责将 JS 对象转换为 JSON 字符串并设置标头(这些是可定制的)
  • 回调函数分别命名为 successerror(还请注意每个回调的参数) - 在 angular v1.5 中已弃用
  • 改用 then 函数.
  • 有关then 用法的更多信息,请参见这里
  • AngularJS version is more concise (especially using .post() method)
  • AngularJS will take care of converting JS objects into JSON string and setting headers (those are customizable)
  • Callback functions are named success and error respectively (also please note parameters of each callback) - Deprecated in angular v1.5
  • use then function instead.
  • More info of then usage can be found here

以上只是一个简单的例子和​​一些提示,请务必查看 AngularJS 文档以获取更多信息:http://docs.angularjs.org/api/ng.$http

The above is just a quick example and some pointers, be sure to check AngularJS documentation for more: http://docs.angularjs.org/api/ng.$http

这篇关于从 jquery $.ajax 到 angular $http的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆