2015-05-21 32 views
0

這裏是我的AngularJS代碼發出請求:POST請求是有效的(狀態200),但未能滿足條件

$scope.add = function(){ // Function used to add a value to list. Value has name, type, and priority. 
    if($scope.thing){ 
     $scope.items.push(
      {name: $scope.thing, 
      type: $scope.worktypeSelection, 
      priority: $scope.prioritySelection, 
      completed: false, 
      comments: '', 
      creator: $scope.username, 
      assignedTo: $scope.assign 
     }); 

     var itemToJson = $scope.items[$scope.items.length - 1]; 

     $http.post('http://localhost:8080/server/todoList/addItem', {itemToJson}) 
     .success(function(response) {alert("success");}) 
     .error(function(response) {alert("fail");}); 

     $scope.thing = ''; 
    } 
    else{ 
     alert("Empty task is not allowed!"); 
    } 
}; 

而且我的Grails控制器:

package server 

import grails.converters.JSON 

class TodoListController { 

    def addItem() { 
     def newItem = new Item(request.JSON) 
     newItem.save(flush: true) 
     render newItem as JSON 
    } 

    def index(){ 
     render Item.list() as JSON 
    } 
} 

而且其領域類:

package server 

class Item { 

    String name 
    String type 
    String priority 
    boolean completed = false 
    String comments 
    String creator 
    String assignedTo 

    static constraints = { 
     name nullable: false 
     priority nullable: true 
     type nullable: true 
     comments nullable: true 
     creator nullable: false 
     assignedTo nullable: false 
    } 
} 

當我開始後,我收到了200從網絡(據稱意味着職位是好的),但後來我得到的輝l結果(警報彈出「失敗」)。我不明白的問題是什麼,如果請求實際上到達服務器

回答

0

的itemToJson已經是JSON對象,

不要放在速滑運動員的肌肉在「{}」

這樣的:

$http.post('http://localhost:8080/server/todoList/addItem', itemToJson) 
+0

非常感謝您的支持,但這並沒有解決問題。雖然很高興知道! – Ajv2324

0

你可以用「然後」的方法試試,我已經有一些問題與錯誤/成功方法:

$http.post('url', data).then(
    function(result) { 
     // success callback 
    }, 
    function(error) { 
     // error callback 
    } 
); 

否則,問題可能是由服務器返回的json不正確。當服務器返回一些內容時,http狀態碼是200.但這並不意味着數據格式良好的JSON。檢查JSON是否正確。

+0

如何檢查從服務器發送的數據? – Ajv2324

+0

只需在發送數據之前打印數據,或者在chrome開發工具中,您可以在網絡選項卡中看到關於HTTP請求的信息。 – Damien

+0

我得到「無請求數據」鉻 – Ajv2324

0

這個問題似乎與CORS和我的瀏覽器有關。我在IE中試過,它工作正常。在意識到這一點之後,我希望在工作了幾個小時之後把頭髮拉出來,然後我下載了this extension用於允許CORS並且現在可以工作的chrome(或多或少有一些扭曲現象,但現在有持久性)。

相關問題