jquery - 从 jquery $.ajax 到 angular $http

标签 jquery ajax angularjs cross-domain 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");
    }
});

现在我试图将其转换为 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;
});

感谢任何帮助。

最佳答案

调用 $http 的 AngularJS 方式如下所示:

$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 字符串并设置 header (可自定义)
  • 回调函数分别命名为successerror(另请注意每个回调的参数)-在angular v1.5中已弃用
  • 改用 then 函数。
  • 可以找到then 用法的更多信息here

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

关于jquery - 从 jquery $.ajax 到 angular $http,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12131659/

相关文章:

javascript - 如何监听元素上的 "particular"动画结束?

jQuery - 对象 [object Object] 没有方法 'on'

jquery - 如何使用 jQuery Draggable 的高级方法

javascript - Cordova JQuery ajax 无法正常工作

javascript - 以 Angular 保存对象数组

jquery kwicks 调整我的图像大小

javascript - 使用Javascript向服务器发送多个请求,直到服务器返回200

c# - jQuery AJAX 回发到 WebMethod 仅返回第一行结果

javascript - Angular POST 请求

angularjs - 根据一天中的时间更改背景 DIV