簡體   English   中英

angularjs序列化表單數據

[英]angularjs serialize form data

我希望在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>

但是控制台上沒有任何內容。 我哪里錯了?

來自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...">

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

演示。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM