2016-03-08 72 views
1

我對我的下面的角碼感到有點沮喪,因爲它不會將JSON數據發送到我在同一臺機器上運行的基於spring boot的微服務。請幫助我!僅供參考,我是JavaScript世界的新手。

$scope.addBook = function() { 
    var data = $.param({ 
     json: JSON.stringify({ 
      name: $scope.bookName, 
      isbn: $scope.isbn, 
      author: $scope.authorName, 
      pages: $scope.pages 
     }) 
    }); 

    var config = { 
     headers : { 
      'Content-Type': 'application/json' 
     } 
    } 

    var result = $http.post('http://localhost:8080/book', data, config); 
    result.success(function (data, status, headers, config) { 
     $scope.result = JSON.stringify({data: data}); 
    }); 
    result.error(function (data, status, header, config) { 
     $scope.result = JSON.stringify({data: data}); 
    }); 
}; 
+0

你得到的錯誤是什麼? –

+0

你在控制檯中得到什麼?你在哪裏得到錯誤?你能夠在成功回調後訪問成功數據嗎? –

回答

1

只是通過你的數據對象是這樣的:

$scope.addBook = function() { 
     var data = 
      { 
       name: $scope.bookName, 
       isbn: $scope.isbn, 
       author: $scope.authorName, 
       pages: $scope.page 
     }; 

     var config = { 
      headers : { 
       'Content-Type': 'application/json' 
      } 
     } 

     var result = $http.post('http://localhost:8080/book', data, config); 
     result.success(function (data, status, headers, config) { 
      $scope.result = JSON.stringify({data: data}); 
     }); 
     result.error(function (data, status, header, config) { 
      $scope.result = JSON.stringify({data: data}); 
     }); 
    }; 

你並不需要字符串化它。如果您的服務正在返回JSON,您可能也可以移除您獲得的結果的字符串化。

+0

我有另一個問題 - XMLHttpRequest無法加載http://127.0.0.1:8080/book。對預檢請求的響應不會通過訪問控制檢查:請求的資源上不存在「訪問控制 - 允許來源」標頭。原因'http:// localhost:63342'因此不被允許訪問。我已經修復使用此鏈接:http://stackoverflow.com/questions/20035101/no-access-control-allow-origin-header-is-present-on-the-requested-resource –

2

你並不需要運行JSON.stringify$.param,只需直接傳遞對象$http.post()。 Angular爲您創建JSON。

0

我認爲$http不發送stingifyed的數據。

嘗試

$scope.addBook = function() { 
    var data = { 
      name: $scope.bookName, 
      isbn: $scope.isbn, 
      author: $scope.authorName, 
      pages: $scope.pages 
     }; 

    $http.post('http://localhost:8080/book', data) 
     .success(function (data, status, headers, config) { 
      $scope.result = JSON.stringify({data: data}); 
     }) 
     .result.error(function (data, status, header, config) { 
      $scope.result = JSON.stringify({data: data}); 
     }); 
}; 
0

數據更改爲以下。它應該工作

var data = $.param({ 
       'name': $scope.bookName, 
       'isbn': $scope.isbn, 
       'author': $scope.authorName, 
       'pages': $scope.pages 
     });