jquery $ .ajax에서 각도 $ http로


122

교차 출처에서 잘 작동하는 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;
});

도움을 주시면 감사하겠습니다.


3
angular.js를 모르지만 faile ()가 함수의 잘못된 이름 일 수 있습니까?
— Bogdan Rybak 2012-08-26

다른 유사한 문제를 발견 stackoverflow.com/questions/11786562/…
— Endless

해결책을 찾았을 수도 있습니다. stackoverflow.com/questions/12111936/… 깊이
— Endless

OPTIONS 요청은 브라우저에서 발행되며 AngularJS / 귀하의 애플리케이션에 투명합니다. OPTION이 성공하면 원래 요청 (POST / GET / 무엇이든)이 따르고 OPTION이 아닌 기본 요청에 대해 코드가 다시 호출됩니다.
— pkozlowski.opensource

요청 방법을 OPTIONS로 변경하는 것은 Angular가 아닐 수 있습니다. CORS 요청을 수행 할 수 있는지 확인하기 위해 브라우저가 확인하는 것일 수 있습니다. 별도의 도메인에 대한 호출을 시도하는 경우 브라우저는 먼저 OPTIONS 요청을 수행하여 허용되는지 확인합니다.
— Ian

답변:


202

$ 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 문자열로 변환하고 헤더를 설정합니다 (사용자 정의 가능).
  • 콜백 함수는 이름이 지정 success되고error (각 콜백의 주 매개 변수를하시기 바랍니다) 각각 - 각 버전 1.5에서 사용되지 않는
  • 사용하다 then 대신 작동합니다.
  • then사용에 대한 자세한 정보는 여기 에서 찾을 수 있습니다.

위의 내용은 간단한 예제와 몇 가지 포인터입니다. 자세한 내용은 AngularJS 문서를 확인하세요. http://docs.angularjs.org/api/ng.$http


2
알아 둘만 한! 그러나 나는 클라이언트 오류를 ​​처리하지 않고 Angular는 Request 메서드를 OPTIONS로 변경합니다. 지원하기 위해 서버 측 작업을해야한다고 생각합니다
— Endless

예, 먼저 서버 측 문제를 해결해야한다고 생각합니다. 그러면 클라이언트 측에서 angular의 $ http를 최대한 활용할 수 있습니다. 아마도 AngularJS가 jQuery와 비교하여 더 많은 / 다른 헤더를 보내고 있기 때문에 추가 OPTIONS 요청을 볼 수 있습니다.
— pkozlowski.opensource

1
참고 : "params :"를 가져 오지만 "data :"가
— 아님

5
params및 dataPARAMS는 URL (쿼리 문자열)에서 생을 마감하면서 데이터 - 요청 본문에 (실제로 몸을 가질 수 요청 유형) :이 다른 것입니다.
— pkozlowski.opensource 2013

"Angular 변경 요청 방법을 OPTIONS. 지원하기 위해 서버 측 작업을 수행해야한다고 생각합니다."같은 문제가 있습니다. angular가 jquery가 추가하지 않는 것은 무엇입니까?
— Andrew Luhring 2015-04-20

1

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

http://www.drtuts.com/ajax-requests-angularjs/



-5

$ .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 웹 API 도메인 간 문제


4
$ .param은 jQuery이므로이를 사용하려면 jQuery를로드해야합니다. $ http transformRequest 인터셉터를 사용하는 jQuery가없는 예제는 pastebin.com/zsn9ASkM
— Brian

@Brian 잠깐만 요, jQuery는 AngularJS의 의존성이 아닌가요? jQuery를 먼저로드하지 않으면 $ http를 사용할 수 없습니다.
— jnm2

2
@ jnm2-아니요, jQuery는 AngularJS의 종속성이 아닙니다. $ http는 Angular $ http 서비스 구성 요소를 나타내며 jQuery의 어떤 것도 아닙니다. AngularJS에는 DOM 조작에 사용할 수있는 "jQuery Lite"가 있지만 매우 제한적입니다. 에서 각도 요소 - jQuery를 사용할 수있는 경우, angular.element는 jQuery를 함수의 별칭입니다. jQuery를 사용할 수없는 경우 angular.element는 "jQuery lite"또는 "jqLite"라고하는 Angular의 기본 제공 jQuery 하위 집합에 위임합니다.
— Brian
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.