从jquery $ .ajax到angular $ http

End*_*ess 121 ajax jquery cross-domain angularjs angular-http

我有这个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");
    }
});
Run Code Online (Sandbox Code Playgroud)

现在我想把它转换成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;
});
Run Code Online (Sandbox Code Playgroud)

任何帮助赞赏.

pko*_*rce 202

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;
});
Run Code Online (Sandbox Code Playgroud)

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

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

有很多事情需要注意:

  • AngularJS版本更简洁(特别是使用.post()方法)
  • AngularJS将负责将JS对象转换为JSON字符串并设置标题(可自定义)
  • 回调函数命名success,并error分别(也请注意每个回调的参数) -不赞成使用,角V1.5
  • 改用then函数.
  • 更多then用法信息可以在这里找到

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

  • `params`和`data`是两个不同的东西:params最终在URL(查询字符串)中而数据在请求体中(仅适用于实际可以拥有body的请求类型). (5认同)
  • 很高兴知道!但是,我不知道我正在处理的客户端错误,Angular将Request方法更改为OPTIONS.我认为我必须做一些服务器端的东西来支持它 (2认同)