2014-10-10 23 views
0

我試圖序列化形式和使用HTTP POST方法將其發送到服務器...jQuery的崗位VS角度使用POST方法

我的代碼的jQuery如下..

var data = $scope.modal.element.find('form').serialize(); 

    $.ajax({ 
     type: "POST", 
     url: "/user/add.html", 
     data: data 
    }).success(function(ret){ 
     $scope.modal.body = $sce.trustAsHtml(ret); 
     $http.get("/user/list.json").success(function(data){ 
      $scope.users = data; 
     }); 
    }); 

上面的代碼工作就好了... ...當我使用的角度後用下面的代碼中的數據...

 var data = $scope.modal.element.find('form').serialize(); 

     $http.post("/user/add.html", data).success(function(html){ 
      $scope.modal.body = $sce.trustAsHtml(html); 
      $http.get("/user/list.json").success(function(data){ 
       $scope.users = data; 
      }); 
     }); 

服務器怪胎......和任何不理解的是變量送過來...... 服務器返回一個錯誤,說我所有的領域都是空的......(它不能解析它)

我已閱讀一些答案,其中涉及編輯窗體的HTML和使用ng-model不幸的是我得到的變量這樣做的自由......

請告訴我是什麼這2種方法之間的區別是......爲什麼一個正在和otherone是不是...

PS:我想用角發佈數據

+1

這很可能是因爲默認的POST Content-Type是用於Angular的application/json和用於jQuery的application/x-www-form-urlencoded。您可以通過修改[$ http](https://docs.angularjs.org/api/ng/service/$http#post)標頭的默認值來改變這一點,如[here]所示(https://gist.github .com/s9tpepper/3328010)或在運行時像$ http show的文檔。同樣的問題和答案[這裏](http://stackoverflow.com/questions/12190166/angularjs-any-way-for-http-post-to-send-request-parameters-instead-of-json)以及 – Lbatson 2014-10-11 00:26:50

+0

你不應該使用angular作爲jQuery的擴展... – Shomz 2014-10-11 01:21:16

+0

thanx @ intothev01d用於指出內容類型差異... – Drmjo 2014-10-11 19:46:36

回答

1

請試試像這樣:

var data = $scope.modal.element.find('form').serialize(); 

    $http({ 
     method: 'POST', 
     url: "/user/add.html", 
     data: data, 
     headers: { 'Content-Type': 'application/x-www-form-urlencoded' } 
    }).success(function(html){ 
     $scope.modal.body = $sce.trustAsHtml(html); 
     $http.get("/user/list.json").success(function(data){ 
      $scope.users = data; 
     }); 
    });