簡體   English   中英

使用Angular JS從多個行輸入字段創建JSON對象

[英]Create JSON object from multiple row input fields using Angular JS

多行輸入字段是

在此處輸入圖片說明

我使用jQuery創建了一種派生JSON的方法

function createReminderJSON() {
         jsonObj = [];
        $("input[class=occasion]").each(function() {

            var occasion = $(this).val();

            if ('' !== occasion) {
                var fname = $('.fname').val();
                var lname = $('.lname').val();

                item = {}
                item["occasion"] = occasion;
                item["firstName"] = fname;
                item["lastName"] = lname;

                jsonObj.push(item);
            }

        });
        console.log(jsonObj);
        $.ajax({
            type : "post",
            contentType : "application/json",
            url : "/add/reminder",
            data : JSON.stringify(jsonObj)
        }); 
    }

創建的JSON是

[{occasion:1,firstName:Tim,lastName:Cook},{occasion:1,firstName:Steve,lastName:Jobs}]

輸入字段的HTML:

<tr>
    <td><input type="text" name="occasion" placeholder="occasion" class="occasion" ng-model="rem.occasion"/></td>
    <td><input type="text" name="firstName" placeholder="fname" class="fname" ng-model="rem.firstName"/><td>
    <td><input type="text" name="lastName" placeholder="lname" class="lname" ng-model="rem.lastName"/><td>
</tr>

ng-click=addReminder()上調用的Angular JS方法是

function Reminder($scope,$http){
        $scope.addReminder = function() {
            var reminders = $scope.rem;
            alert(reminders);
            $http.post('/add/reminder', reminders).success(function(data) {
                alert("Success!");
            });
        }
    }

是否需要angular.forEach? 我如何使用Angular JS silmilar到jQuery來創建JSON。 當我嘗試單行輸入時,警報使我undefined

您只需要在控制器中聲明一個空對象。

$scope.rem = {};

不,這不對。 請記住,JSON代表Javascript Object Notation。 這是描述對象的方式。 因此,您的AngularJS控制器中的模型-例如,通過POST“在線”對其進行序列化后,它們就會看起來像您想要的JSON。

這是演示的小提琴: http : //jsfiddle.net/358uqccy/3/ | json | json過濾器將對象轉換為JSON,以向您顯示模型的JSON始終可用。

暫無
暫無

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

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