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

助けていただければ幸いです。

4

4 に答える 4

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文字列に変換し、ヘッダーを設定します(これらはカスタマイズ可能です)
  • コールバック関数にはそれぞれ名前が付けられsuccesserrorそれぞれ(各コールバックのパラメーターにも注意してください)-Angularv1.5では非推奨
  • then代わりに関数を使用してください。
  • then使用法の詳細については、こちらをご覧ください

上記は簡単な例であり、いくつかの指針です。詳細については、AngularJSのドキュメントを確認してください:http ://docs.angularjs.org/api/ng.$http

于 2012-08-26T16:40:49.257 に答える
1

AngularJsでhttpサービスを使用してajaxリクエストを実装できます。これは、リモートサーバーからのデータの読み取り/読み込みに役立ちます。

$httpサービスメソッドを以下に示します。

 $http.get()
 $http.post()
 $http.delete()
 $http.head()
 $http.jsonp()
 $http.patch()
 $http.put()

例の1つ:

    $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/

于 2016-09-16T14:32:09.483 に答える
0

あなたはこれを使うことができます:

「angular-post-fix」をダウンロードします:「^0.1.0」

次に、Angularモジュールを宣言しながら、依存関係に「httpPostFix」を追加します。

参照:https ://github.com/PabloDeGrote/angular-httppostfix

于 2017-03-30T10:08:49.900 に答える
-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.NETWebAPIクロスドメインの問題

于 2014-03-11T16:31:29.517 に答える