从jquery$.ajax到$http

我有一段jQuery代码,它在交叉源代码中运行良好:

jQuery.ajax({
url:“http://example.appspot.com/rest/app",
类型:“POST”,
数据:JSON.stringify({“foo”:“bar}),
数据类型:“json”,
contentType:“应用程序/json;字符集=utf-8”,
成功:功能(响应){
控制台日志(“成功”);
},
错误:函数(响应){
console.log(“失败”);
}
});

现在我尝试将其转换为Angular.js代码,但没有成功:

$http({
url:“http://example.appspot.com/rest/app",
数据类型:“json”,
方法:“张贴”,
数据:JSON.stringify({“foo”:“bar}),
标题:{
“内容类型”:“应用程序/json;字符集=utf-8”
}
}).成功(功能(响应){
$scope.response=响应;
}).错误(函数(错误){
$scope.error=错误;
});

谢谢你的帮助

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

$http({
url:“http://example.appspot.com/rest/app",
方法:“张贴”,
数据:{“foo”:“bar”}
}).then(函数成功回调(响应){
//将异步调用此回调
//当响应可用时
$scope.data=response.data;
},函数errorCallback(响应){
//发生错误时异步调用
//或服务器返回带有错误状态的响应。
$scope.error=response.statusText;
});

或者可以使用快捷方式编写更简单的代码:

$http.post(“http://example.appspot.com/rest/app“,{“foo”:“bar”})
.然后(successCallback,errorCallback);

有很多事情需要注意:

  • AngularJS版本更简洁(特别是使用.post()方法)
  • AngularJS将负责将JS对象转换为JSON字符串并设置标题(可自定义)
  • 回调函数分别命名为successerror(也请注意每个回调函数的参数)-在angular v1.5中已弃用
  • 使用然后改用函数
  • 有关用法的更多信息,请参见此处

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

发表评论