2012-08-27 33 views
5

我希望以angularjs序列化表單數據。以下是控制器的代碼:angularjs序列化表單數據

function SearchCtrl($scope, $element, $http) { 
     $scope.url = 'php/search.php'; 
     $scope.submit = function() { 
      var elem = angular.element($element); 
      //var dt = $(elem.parent()).serialize(); 
      console.log($(elem.parent()).serialize()); 
      $http({ 
       method: 'POST', 
       url: $scope.url, 
       data: 'first=hgf&last=ghfgh', 
       headers: {'Content-Type': 'application/x-www-form-urlencoded'} 
      }).success(function(data, status) { 
       $scope.status = status; 
       $scope.data = data; 
       $scope.result = data; // Show result from server in our <pre></pre> element 
       //var elem = angular.element(e.srcElement); 
       //alert($(elem.parent()).serialize()); 
      }).error(function(data, status) { 
       $scope.data = data || "Request failed"; 
       $scope.status = status; 
      }); 
      return false; 
     }; 
} 

編輯:

<!DOCTYPE html> 
<html ng-app> 
<head> 
<title>Search form with AngualrJS</title> 
     <script src="../angular-1.0.1.min.js"></script> 
     <script src="http://code.jquery.com/jquery.min.js"></script> 
     <script src="js/search.js"></script> 



</head> 
<body> 
     <div> 
     <form ng-controller="SearchCtrl" ng-submit="submit()"> 
      <label>Search:</label> 
      <input type="text" ng-model="keywords" placeholder="enter name..."> 
      <input type="text" ng-model="desc" placeholder="enter description..."> 
      <button type="submit">Search</button> 
      <p>Try for example: "php" or "angularjs" or "asdfg"</p> 
     </form> 
<pre ng-model="result"> 
{{result}} 
</pre> 
    </div> 
</body> 

</html> 

但沒有獲取打印在控制檯上。我哪裏錯了?

+0

編輯的內容包含html。 – z22

+0

我不知道爲什麼使用$(elem.parent())。serialize())而不是'$(elem).serialize()'。這裏的$元素不是'

'嗎? – raina77ow

+0

我試過用$(elem).serialize(),仍然沒有結果!我做什麼shpuld? – z22

回答

8

doc

對於表單元素的值要包含在序列化的字符串, 的元素必須有一個name屬性。

在您的HTML輸入中沒有名稱,因此serialize返回空字符串。喜歡的東西解決這個問題...

<input type="text" name="keywords" ng-model="keywords" placeholder="enter name..."> 
<input type="text" name="desc" ng-model="desc" placeholder="enter description..."> 

而且,順便說一句,你不必角$element包裝成jQuery函數:$element.serialize()將工作正常。

Demo.

+0

$ element.serialize()不能單獨工作,它給我在Chrome控制檯中沒有方法'serialize'錯誤Object [[object HTMLFormElement]] – z22