从jQuery的$就到角$ HTTP [英] from jquery $.ajax to angular $http

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

问题描述

我有这块jQuery的code工作正常跨产地:

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 code没有任何成功:

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

任何帮助AP preciated。

Any help appreciated.

推荐答案

在AngularJS调用方式$ HTTP看起来像:

The AngularJS way of calling $http would look like:

$http({
    url: "http://example.appspot.com/rest/app",
    method: "POST",
    data: {"foo":"bar"}
}).success(function(data, status, headers, config) {
    $scope.data = data;
}).error(function(data, status, headers, config) {
    $scope.status = status;
});

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

or could be written even simpler using shortcut methods:

$http.post("http://example.appspot.com/rest/app", {"foo":"bar"})
.success(function(data, status, headers, config) {
    $scope.data = data;
}).error(function(data, status, headers, config) {
    $scope.status = status;
});

有事情要注意数量:

  • 在AngularJS版本更简洁(特别是在使用。员额()方法)
  • 在AngularJS将转换JS对象转换成JSON字符串,并设置标题(这些都是定制)
  • 照顾
  • 在回调函数被命名为成功错误分别为(请注意每个回调的参数)
  • 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)

以上只是一个简单的例子和​​一些指针,一定要检查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的$就到角$ HTTP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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