我有这段 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 (可自定义)
- 回调函数分别命名为
success
和error
(另请注意每个回调的参数)-在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/