【问题标题】:from jquery $.ajax to angular $http从 jquery $.ajax 到 angular $http
【发布时间】:2012-08-21 07:57:49
【问题描述】:

我有这段 jQuery 代码可以很好地跨源:

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

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

任何帮助表示赞赏。

【问题讨论】:

  • 不知道 angular.js 但可能 faile() 是一个错误的函数名称?
  • 发现另一个类似问题stackoverflow.com/questions/11786562/…
  • 可能找到了解决方案stackoverflow.com/questions/12111936/…需要深入挖掘...
  • OPTIONS 请求将由浏览器发出,它对 AngularJS/您的应用程序是透明的。如果 OPTION 成功,原始请求(POST/GET/whatever)将随之而来,并且您的代码将被回调为主请求而不是 OPTION 请求。
  • 可能不是 Angular 将请求方法更改为 OPTIONS。可能是您的浏览器检查它是否可以执行 CORS 请求。如果您尝试调用一个单独的域,您的浏览器将首先发出一个 OPTIONS 请求以查看是否允许。

标签: jquery ajax angularjs cross-domain angular-http


【解决方案1】:

AngularJS 调用 $http 的方式如下:

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

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

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

有很多事情需要注意:

  • AngularJS 版本更简洁(尤其是使用 .post() 方法)
  • AngularJS 将负责将 JS 对象转换为 JSON 字符串并设置标题(可自定义)
  • 回调函数分别命名为successerror(还请注意每个回调的参数)- Angular v1.5 中已弃用
  • 请改用then 函数。
  • 更多then使用信息请见here

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

【讨论】:

  • 很高兴知道!但是我不关心我正在处理的客户端错误,Angular 将 Request 方法更改为 OPTIONS。认为我必须做一些服务器端的事情来支持它
  • 是的,我想你需要先解决服务器端的问题。然后,您将能够在客户端享受 angular 的 $http 的全部功能。可能您会看到一个额外的 OPTIONS 请求,因为与 jQuery 相比,AngularJS 发送了更多/不同的标头。
  • 注意:在获取“参数:”而不是“数据:”中,请参阅stackoverflow.com/questions/13760070/…
  • paramsdata 是两个不同的东西:参数最终出现在 URL(查询字符串)中,而数据 - 在请求正文中(仅适用于实际上可以具有正文的请求类型)。跨度>
  • "Angular 将 Request 方法更改为 OPTIONS。认为我必须做一些服务器端的事情来支持它" 我遇到了同样的问题,Angular 增加了什么而 jquery 没有?
【解决方案2】:

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

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

 $http.get()
 $http.post()
 $http.delete()
 $http.head()
 $http.jsonp()
 $http.patch()
 $http.put()

其中一个例子:

    $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/

【讨论】:

    【解决方案3】:

    你可以用这个:

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

    然后在声明 Angular 模块时将“httpPostFix”添加到您的依赖项中。

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

    【讨论】:

      【解决方案4】:

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

       $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

      【讨论】:

      • 请注意 $.param 是 jQuery,因此您需要加载 jQuery 才能使用它。有关使用 $http transformRequest 拦截器的无 jQuery 示例,请参阅pastebin.com/zsn9ASkM
      • @Brian 等一下,jQuery 不是 AngularJS 的依赖项吗?如果没有首先加载 jQuery,你将永远不会拥有 $http。
      • @jnm2 - 不,jQuery 不是 AngularJS 的依赖项。 $http 指的是Angular $http service component,而不是 jQuery 中的任何东西。 AngularJS 确实有一个“jQuery Lite”可用于操作 DOM,但它非常有限。来自Angular element - 如果 jQuery 可用,则 angular.element 是 jQuery 函数的别名。如果 jQuery 不可用,则 angular.element 委托给 Angular 的内置 jQuery 子集,称为“jQuery lite”或“jqLit​​e”。
      猜你喜欢
      • 1970-01-01
      • 2014-05-09
      • 1970-01-01
      • 2014-11-01
      • 1970-01-01
      • 2022-11-10
      • 2014-01-18
      • 2015-11-11
      • 2013-12-30
      相关资源
      最近更新 更多