小编典典

从jquery $ .ajax到angular $ http

angularjs

我有这段可以很好地跨源工作的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;
});

任何帮助表示赞赏。


阅读 290

收藏
2020-07-04

共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字符串并设置标头(可自定义)
  • 回调函数分别命名success和命名error(也请注意每个回调的参数)-angular v1.5中已弃用
  • 使用then功能代替。
  • 使用的更多信息then可以在这里找到

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

2020-07-04