从jquery的$.ajax到angular的$http
从jquery的$.ajax到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; });
希望有人能帮助我。
admin 更改状态以发布 2023年5月20日
我们可以使用AngularJs中的http服务来实现ajax请求,从而帮助读取/加载远程服务器上的数据。
$http服务的方法如下所示:
$http.get() $http.post() $http.delete() $http.head() $http.jsonp() $http.patch() $http.put()
其中一个例子:
$http.get("sample.php") .success(function(response) { $scope.getting = response.data; // response.data is an array }).error(){ // Error callback will trigger });
使用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