У меня есть этот кусок кода 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");
}
});
Теперь я tring, чтобы преобразовать это в 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 будет выглядеть так:
$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);
Есть несколько замечаний:
success
и error
соответственно (также обратите внимание на параметры каждого обратного вызова) - Устаревшие в angular v1.5then
функцию.then
можно найти здесьВышеприведенный пример - просто быстрый пример и некоторые указатели, обязательно проверьте документацию по AngularJS для более: http://docs.angularjs.org/api/ng.$http
Вы можете использовать это:
Скачайте "angular -post-fix": "^ 0.1.0"
Затем добавьте 'httpPostFix' к вашим зависимостям, объявив модуль angular.
Мы можем реализовать запрос ajax, используя http-сервис в AngularJs, который помогает читать/загружать данные с удаленного сервера.
$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
});
вы можете использовать $.param для назначения данных:
$http({
url: "http://example.appspot.com/rest/app",
method: "POST",
data: $.param({"foo":"bar"})
}).success(function(data, status, headers, config) {
$scope.data = data;
}).error(function(data, status, headers, config) {
$scope.status = status;
});
посмотрите на это: Проблема с несколькими доменами AngularJS + ASP.NET