我有一段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;
});

Any help appreciated.

推荐答案

The AngularJS way of calling $http would look like:

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

or could be written even simpler using shortcut methods:

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

有很多事情需要注意:

  • AngularJS版本更简洁(特别是使用.post()方法)
  • AngularJS将负责将JS对象转换为JSON字符串,并设置标题(可自定义)
  • 回调函数分别命名为successerror(也请注意每个回调函数的参数)——在angular v1中不推荐使用.5.
  • use then function instead.
  • 有关then用法的更多信息,请参阅here

The above is just a quick example and some pointers, be sure to check AngularJS documentation for more: http://docs.angularjs.org/api/ng.$http

Jquery相关问答推荐

如何在不使用点击事件 bootstrap 程序模式的情况下使用弹出窗口 bootstrap 程序显示用户详细信息?

如果文本框内容在 X 秒内没有更改,则进行 post 调用

提高 jQuery Select 器性能的好方法?

仅在 _some 字段上通过 Enter 键禁用表单提交

jquery清除输入默认值

了解 Backbone.js REST 调用

SCRIPT7002:XMLHttpRequest:网络错误 0x2ef3,由于错误 00002ef3 无法完成操作

window.onbeforeunload 和 window.onunload 在 Firefox、Safari、Opera 中不起作用?

jQuery 序列化不注册复选框

iframe 仅显示页面的特定部分

使用jquery设置di​​v标签的值

使用带有 HTML 表格的 jQuery UI 可排序

jQuery Force 为 iframe 设置 src 属性

所有但不是jQuery Select 器

什么时候应该使用 jQuery deferred 的then方法,什么时候应该使用pipe方法?

如何使用 jQuery 取消设置元素的 CSS 属性?

Chrome 中的 AJAX 发送选项而不是 GET/POST/PUT/DELETE?

自调用函数前的分号?

jquery在cookie中保存json数据对象

使用 jQuery 检测元素内容的变化