首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从jquery $.ajax到angular $http

从jquery $.ajax到angular $http
EN

Stack Overflow用户
提问于 2012-08-27 00:08:40
回答 3查看 141.7K关注 0票数 122

我有一段jQuery代码,它可以很好地跨源代码工作:

代码语言:javascript
复制
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代码,但没有成功:

代码语言:javascript
复制
$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;
});

感谢您的帮助。

EN

回答 3

Stack Overflow用户

发布于 2016-09-16 22:32:09

在AngularJs中使用http服务实现ajax请求,可以方便地从远程服务器读取/加载数据。

下面列出了$http服务方法:

代码语言:javascript
复制
 $http.get()
 $http.post()
 $http.delete()
 $http.head()
 $http.jsonp()
 $http.patch()
 $http.put()

其中一个示例:

代码语言:javascript
复制
    $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/

票数 1
EN

Stack Overflow用户

发布于 2017-03-30 18:08:50

您可以使用以下命令:

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

然后在声明angular模块时将'httpPostFix‘添加到您的依赖项中。

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

票数 0
EN

Stack Overflow用户

发布于 2014-03-12 00:31:30

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

代码语言:javascript
复制
 $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 Cross-Domain Issue

票数 -5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12131659

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档