如何从JSON数据添加数据

时间:2014-05-05 08:41:54

标签: javascript json knockout.js knockout-2.0

在此fiddleview appointmnets标签中,有一个可用的医院下拉菜单,其中包含3个字段A,B,c。

现在我想从我从JSON获得的值中创建这个下拉列表。

这是我的JSON数据

   {
    "doctors": [
        {
            "id": 1,
            "schedules": [
                {
                    "id": 1,
                    "totime": "13:19",
                    "dayId": 1,
                    "locati‌​on": "Somajiguda",
                    "fromtime": "12:19",
                    "hospitalId": 5,
                    "day": "Monday",
                    "hospital": "Yas‌​hoda"
                }
            ],
            "username": "doctor",
            "degree": "MBBS,MD",
            "email": "a@b.com",
            "image‌​Path": "imagePathValue",
            "department": "Bio-Chemistry",
            "name": "doctor",
            "userid": 4,
            "g‌​ender": "Male",
            "mobile": "1234567890"
        }
    ]
}

在上面的JSON中,医院"hospital": "Yas‌​hoda"有一个值,所以我只想要" Yas hoda"在上面的JSON中,还有totime和fromtime字段。我能够得到那些字段,但我没有在下拉列表中获得医院名称。任何人都可以在这里投入一些光。

这是我的更新fiddle,以下是js代码

var DocSchedule = function(id, day, fromtime, totime, hospital, hospitalId) {
    this.id = ko.observable(id);
    this.day = ko.observable(day);
    this.fromtime = ko.observable(fromtime);
    this.totime = ko.observable(totime);
    this.hospital = ko.observable(hospital);
    this.hospitalId = ko.observable(hospitalId);
}

var iter = 0;


//var genderOptions = ['Male', 'Female']; 
//var degreeOptions=['BDS','DA(Anaesthesia)','MBBS','MBBS,MD','MBBS,MD(Med)PMCH','MBBS,MD,FNB','MBBS,MS(ENT)','MD,DM,FISC','MD,MS,PhD,DSc','MDS(Oral Surgery)','MS(OPHTH),FICS','MS,DNB,MRCS(Edin),MCh(GASTRO)'] 
//var departmentOptions=['Anesthesiology','Bio-Chemistry','Cardiac Rehab Yoga','Cardio Thoracic Surgery','Cardiology','Chest Physician','Cosmetic Plastic and Hand Surgery','Critical Care','Dental&Facio maxillary Surgery','Dermatology','Diabetology','Dietary Services','Emergency Medicine','Endocrinology','Endoscopic,Head & Neck Surgery','Endoscopy','Gastroenterology','Gastrointestinal Medicine','General Medicine','General Surgery','Geriatrics','Gynecology','Hematology','Internal Medicine','Interventional Radiology','Laboratory Medicine','Laparoscopic Surgery','Medical Oncology','Micro-Biology','Nephrology','Neuro-Surgery','Neurology','Nuclear Medicine','Nuclear Medicinee','Obstetrics and Gynecology','Ophthalmology','Orthopedics & Traumatology','Otorhinolaryngology','Pathology','Pediatric Cardiology','Pediatric Surgery','Pediatrics','Physician','Physiotherapy','Psychiatry','Pulmonology','Radio-Diagnosis','Radiology','Rheumatology','Surgical Gastro-Enterology','Surgical Oncology','Urology','Vascular Surgery'] 
var Doctor = function(nameParam, usernameParam) {
    this.name = nameParam;
    this.username = usernameParam;
};
var doctors = [];

var Patientp = function() {
    this.id = ko.observable('');
    this.name = ko.observable('');
    this.degree = ko.observable('');
    this.gender = ko.observable('');
    //this.consultant= ko.observableArray(consultantArrValue); 
    this.username = ko.observable('');
    this.password = ko.observable('');
    this.email = ko.observable('');
    this.mobile = ko.observable('');
    this.imgFile = ko.observable('');
    this.imgSrc = ko.observable('');
    this.imagePath = ko.observable('');
    this.userid = ko.observable('');
    this.department = ko.observable('');
    //this.consultant= ko.observableArray(consultantArrValue); 
    //this.consultant= ko.observable(consultantValue); 



}


var projectUrl = $('#projectUrl').val();
var pat = new Patientp();
docp = new DocSchedule();

pat.imgFile = 'imagefileValue';
pat.imagePath = 'imagePathValue';


$.ajax({
    type: "GET",
    url: projectUrl + "getDoctors",
    dataType: "json",
    jsonp: true,
    async: false,
    success: function(data) {
        //alert(data); 
        $.each(data.doctors, function(index, currPat) {
            var doc = new Doctor(currPat.name, currPat.username);
            doctors.push(doc);
            if (currPat.userid == "${IDis}") {
                console.log(currPat.degree);
                pat.name = currPat.name;
                pat.username = currPat.username;
                pat.password = "";
                pat.email = currPat.email;
                pat.mobile = currPat.mobile;
                pat.gender = currPat.gender;
                pat.department = currPat.department;
                pat.degree = currPat.degree;
                pat.imgSrc = currPat.imagePath;
                pat.userid = currPat.userid;
                pat.id = currPat.id;
                $.each(currPat.schedules, function(index1, currPat1) {
                    //console.log(currPat1.totime); 
                    docp.fromtime = currPat1.fromtime;
                    docp.totime = currPat1.totime;
                    docp.hospital = currPat1.hospital;
                });
            }
        });
    }
});
/* var jsonobject=ko.utils.parseJson(test); 
$.each(jsonobject.patients,function(i,item){ 
var patient1 = new Patient(item.id, item.name, item.address, item.gender,item.consultant,item.username,"",item.email,item.mobile,"","",item.userid,item.imagePath); 
self.patients.push(patient1);   
});  */
//var patp=new Patientp(); 
//ko.applyBindings(patp); 

function vm() {
    var self = this;
    self.genderOptions = ['Male', 'Female'];
    self.hospitalOptions = ['Yashoda'];
    self.degreeOptions = ['BDS', 'DA(Anaesthesia)', 'MBBS', 'MBBS,MD', 'MBBS,MD(Med)PMCH', 'MBBS,MD,FNB', 'MBBS,MS(ENT)', 'MD,DM,FISC', 'MD,MS,PhD,DSc', 'MDS(Oral Surgery)', 'MS(OPHTH),FICS', 'MS,DNB,MRCS(Edin),MCh(GASTRO)']
    self.departmentOptions = ['Anesthesiology', 'Bio-Chemistry', 'Cardiac Rehab Yoga', 'Cardio Thoracic Surgery', 'Cardiology', 'Chest Physician', 'Cosmetic Plastic and Hand Surgery', 'Critical Care', 'Dental&Facio maxillary Surgery', 'Dermatology', 'Diabetology', 'Dietary Services', 'Emergency Medicine', 'Endocrinology', 'Endoscopic,Head & Neck Surgery', 'Endoscopy', 'Gastroenterology', 'Gastrointestinal Medicine', 'General Medicine', 'General Surgery', 'Geriatrics', 'Gynecology', 'Hematology', 'Internal Medicine', 'Interventional Radiology', 'Laboratory Medicine', 'Laparoscopic Surgery', 'Medical Oncology', 'Micro-Biology', 'Nephrology', 'Neuro-Surgery', 'Neurology', 'Nuclear Medicine', 'Nuclear Medicinee', 'Obstetrics and Gynecology', 'Ophthalmology', 'Orthopedics & Traumatology', 'Otorhinolaryngology', 'Pathology', 'Pediatric Cardiology', 'Pediatric Surgery', 'Pediatrics', 'Physician', 'Physiotherapy', 'Psychiatry', 'Pulmonology', 'Radio-Diagnosis', 'Radiology', 'Rheumatology', 'Surgical Gastro-Enterology', 'Surgical Oncology', 'Urology', 'Vascular Surgery']
    self.person = pat;
    self.schedule = docp;

    self.schedules = ko.observableArray([new DocSchedule(iter)]);
    self.addSlot = function() {
        console.log(self.schedules.length);
        iter++;
        var docSchedule = new DocSchedule(iter);
        self.schedules.push(docSchedule);
    };

    self.removeSlot = function() {
        console.log('removed');
        self.schedules.remove(this);
    }

};
var viewModel = new vm();
ko.applyBindings(viewModel);
$('#saveButton').click(function() {
    alert('savebutton');
    var testjson = ko.toJSON(pat);
    console.log(testjson);
    var formdata = new FormData();
    formdata.append("doctormetada", testjson);
    console.log(projectUrl + "updateDoctor");
    $.ajax({
        url: projectUrl + "updateDoctor",
        type: "POST",
        data: formdata,
        processData: false,
        contentType: false,
        success: function(res) {
            formdata = new FormData();
            //self.doctor(new Doctor()); 
        }

    });

});

2 个答案:

答案 0 :(得分:1)

我刚刚更改了你的html代码,现在正在运行

 <select class="span8" name="hospital" 
                data-bind="options: $root.hospitalOptions,value: docp.hospital,optionsCaption: 'Select Hospital'"
                data-required="true" data-trigger="change">
            </select>

请参阅link

答案 1 :(得分:0)

试试这个:

HTML

<div style="padding-bottom: 9px; overflow: hidden" class="tab-content">
    <div id="Profile" class="tab-pane active">
        Profile

                        <div class="span6">
                             <p>
                                 <label class="control-label" for="inputIcon">Name :</label>
                                 <input class="span8" type="text" data-bind="value: doctor.name"
                                     data-required="true" data-trigger="change" name="name">
                             </p>
                             <p>
                                 <label class="control-label" for="inputIcon">Department :</label>
                                 <select class="span8" name="department"
                                     data-bind="options: departmentOptions, value: doctor.department, optionsCaption: 'Select Department'"
                                     data-required="true" data-trigger="change">
                                 </select>
                             </p>
                             <p>
                                 <label class="control-label" for="inputIcon">Gender :</label>
                                 <select class="span8" name="gender"
                                     data-bind="options: genderOptions, value: doctor.gender, optionsCaption: 'Select Gender'"
                                     data-required="true" data-trigger="change">
                                 </select>
                             </p>
                             <p>
                                 <label class="control-label" for="inputIcon">Degree :</label>
                                 <select class="span8" name="degree"
                                     data-bind="options: degreeOptions, value: doctor.degree, optionsCaption: 'Select Degree'"
                                     data-required="true" data-trigger="change">
                                 </select>
                             </p>
                             <p>
                                 <label class="control-label" for="inputIcon">Username :</label>
                                 <input class="span8" type="text"
                                     data-bind="value: doctor.username"
                                     name="username" data-required="true"
                                     data-trigger="change"
                                     data-remote="/MoDoc/isUserNameExists"
                                     data-remote-method="GET">
                             </p>
                             <p>
                                 <label class="control-label" for="inputIcon">Password :</label>
                                 <input class="span8" type="password"
                                     data-bind="value: doctor.password"
                                     name="password"
                                     data-required="true"
                                     data-trigger="change">
                             </p>
                             <p>
                                 <label class="control-label" for="inputIcon">Mobile :</label>
                                 <input class="span8" type="text" data-bind="value: doctor.mobile"
                                     data-type="number"
                                     data-minlength="10"
                                     data-required="true"
                                     data-trigger="change" data-type="phone" name="mobile">
                             </p>
                             <p>
                                 <label class="control-label" for="inputIcon">Email address :</label>
                                 <input class="span8" type="text"
                                     data-bind="value: doctor.email" data-required="true"
                                     data-trigger="change" data-type="email" name="email">
                             </p>
                         </div>
        <div class="span6">
            <!--<div data-bind="template: {name: 'profileImageTemplate'}"></div>    -->
            <div style="margin-top: 28px;">
                <div class="fileupload fileupload-new" data-provides="fileupload">
                    <div data-bind="if: doctor.imgSrc">
                        <div class="fileupload-new thumbnail" style="width: 150px; height: 150px;">
                            <img data-bind="attr: { src: doctor.imgSrc }" />
                        </div>
                    </div>
                    <div data-bind="ifnot: doctor.imgSrc">
                        <div class="fileupload-new thumbnail" style="width: 150px; height: 150px;">
                            <img src="ui_resources/img/profile_pic.png" />
                        </div>
                    </div>
                    <div class="fileupload-preview fileupload-exists thumbnail" style="max-width: 150px; max-height: 150px; line-height: 20px;"></div>
                    <div>
                        <span class="btn btn-file"><span class="fileupload-new">Select image</span><span class="fileupload-exists">Change</span><input type="file" data-bind=" file: doctor.imgFile, fileObjectURL: doctor.imgSrc" /></span>
                        <a href="#" class="btn fileupload-exists" data-dismiss="fileupload">Remove</a>
                    </div>
                </div>



            </div>
        </div>
        <div align="center" class="span12">
            <button class="btn btn-primary" id="saveButton">
                <i class="icon-ok icon-white"></i>Save
            </button>
            <button class="btn">
                <i class="icon-remove"></i>Cancel
            </button>
        </div>
    </div>
    <div id="appointments" class="tab-pane ">
        Appointments
        <form id="addDoctorSchedules" data-validate="parsley">
            <table width="100%" cellspacing="0" cellpadding="0" border="0">
                <thead>
                    <tr>
                        <th valign="middle" align="left" style="border-bottom: #edf6f9 solid 1px; border-top: #edf6f9 solid 1px; width: 222px;">Week Day</th>
                        <th align="center" id="to1">From Time</th>
                        <th align="center" id="Td1">To Time</th>
                        <th align="center" id="Td2">Available Hospital</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody data-bind='foreach: schedules'>
                    <tr>
                        <td width="125" valign="middle" align="left" style="border-bottom: #edf6f9 solid 1px; border-top: #edf6f9 solid 1px;">
                            <select class="span8" name="day"
                                data-bind="options: $parent.weekdays, value: day, optionsCaption: 'Select Day'" data-required="true" data-trigger="change">
                            </select>
                        </td>
                        <td align="center" id="Td3">
                            <input type="text" data-format="hh:mm" data-bind="value: fromtime()" style="width: 82px">
                        </td>
                        <td align="center" id="Td4">
                            <input type="text" data-format="hh:mm" data-bind="value: totime()" style="width: 82px">
                        </td>
                        <td align="center" id="Td8">
                            <select class="span8" name="hospital"
                                data-bind="options: $parent.hospitalOptions, value: hospital, optionsCaption: 'Select Hospital'" data-required="true" data-trigger="change">
                            </select>
                        </td>
                        <td>
                            <button class="btn btn-primary" type="button" data-bind="click: $parent.addSlot" value="Add">Add Timing</button>
                            <a href='#' class="btn btn-primary" data-bind='click: $parent.removeSlot'>Remove</a>
                        </td>
                    </tr>
                </tbody>
            </table>
        </form>
    </div>
</div>

JavsScript

var Model;
(function (Model) {
    var Doctor = (function () {
        function Doctor(data) {
            if(data != null) {
                this.id = ko.observable(data['id']);
                this.name = ko.observable(data['name']);
                this.degree = ko.observable(data['degree']);
                this.gender = ko.observable(data['gender']);
                this.username = ko.observable(data['username']);
                this.password = ko.observable(data['password']);
                this.email = ko.observable(data['email']);
                this.mobile = ko.observable(data['mobile']);
                this.imgFile = ko.observable(data['imgFile']);
                this.imgSrc = ko.observable(data['imgSrc']);
                this.imagePath = ko.observable(data['imagePath']);
                this.userid = ko.observable(data['userid']);
                this.department = ko.observable(data['department']);
            } else {
                this.id = ko.observable('');
                this.name = ko.observable('');
                this.degree = ko.observable('');
                this.gender = ko.observable('');
                this.username = ko.observable('');
                this.password = ko.observable('');
                this.email = ko.observable('');
                this.mobile = ko.observable('');
                this.imgFile = ko.observable('');
                this.imgSrc = ko.observable('');
                this.imagePath = ko.observable('');
                this.userid = ko.observable('');
                this.department = ko.observable('');
            }
        }
        return Doctor;
    })();
    Model.Doctor = Doctor;    
    var Schedule = (function () {
        function Schedule(data) {
            if(data != null) {
                this.id = ko.observable('' + Schedule._id++);
                this.day = ko.observable(data['day']);
                this.fromtime = ko.observable(data['fromtime']);
                this.totime = ko.observable(data['totime']);
                this.hospital = ko.observable(data['hospital']);
                this.hospitalId = ko.observable(data['hospitalId']);
            } else {
                this.id = ko.observable('' + Schedule._id++);
                this.day = ko.observable('');
                this.fromtime = ko.observable('');
                this.totime = ko.observable('');
                this.hospital = ko.observable('');
                this.hospitalId = ko.observable('');
            }
        }
        Schedule._id = 0;
        return Schedule;
    })();
    Model.Schedule = Schedule;    
})(Model || (Model = {}));

var projectUrl = $('#projectUrl').val();

        $.ajax({
            type: "GET",
            url: projectUrl + "getDoctors",
            dataType: "json",
            jsonp: true,
            async: false,
            success: function (data) {
                //alert(data);
                $.each(data.doctors, function (index, currPat) {
                    var doc = new Doctor(currPat.name, currPat.username);
                    doctors.push(doc);
                    if (currPat.userid == "4") {
                        console.log(currPat.degree);
                        pat.name = currPat.name;
                        pat.username = currPat.username;
                        pat.password = "";
                        pat.email = currPat.email;
                        pat.mobile = currPat.mobile;
                        pat.gender = currPat.gender;
                        pat.department = currPat.department;
                        pat.degree = currPat.degree;
                        pat.imgSrc = currPat.imagePath;
                        pat.userid = currPat.userid;
                        pat.id = currPat.id;
                        $.each(currPat.schedules, function (index1, currPat1) {
                            //console.log(currPat1.totime);
                            docp.fromtime = currPat1.fromtime;
                            docp.totime = currPat1.totime;
                            docp.hospital = currPat1.hospital;
                        });
                    }
                });
            }
        });

        var data = {
            "doctors": [
                {
                    "id": 1,
                    "schedules": [
                      {
                          "id": 1,
                          "totime": "13:19",
                          "dayId": 1,
                          "location": "Somajiguda",
                          "fromtime": "12:19",
                          "hospitalId": 5,
                          "day": "Monday",
                          "hospital": "Yashoda"
                      }
                    ], "username": "doctor",
                    "degree": "MBBS,MD",
                    "email": "sukant@iconma.com",
                    "imagePath": "imagePathValue",
                    "department": "Bio-Chemistry",
                    "name": "doctor",
                    "userid": 4,
                    "gender": "Male",
                    "mobile": "1234567890"
                }]
        };
        var doctor = data.doctors[0];
        var doc = new Model.Doctor(doctor);
        doc.imgFile = 'imagefileValue';
        doc.imagePath = 'imagePathValue';

        var schedules = [];
        for (var i = 0; i < doctor.schedules.length; i++) {
            schedules.push(new Model.Schedule(doctor.schedules[i]));
        }

        var hospitals = [];
        for (var i = 0; i < schedules.length; i++) {
            hospitals.push(schedules[i].hospital);
        }


        function vm() {
            var self = this;
            self.genderOptions = ['Male', 'Female'];
            self.weekdays = ["Monday","Tuesday","Wednesday","Thursday", "Friday","Saturday","Sunday"]
            self.hospitalOptions = hospitals;
            self.degreeOptions = ['BDS', 'DA(Anaesthesia)', 'MBBS', 'MBBS,MD', 'MBBS,MD(Med)PMCH', 'MBBS,MD,FNB', 'MBBS,MS(ENT)', 'MD,DM,FISC', 'MD,MS,PhD,DSc', 'MDS(Oral Surgery)', 'MS(OPHTH),FICS', 'MS,DNB,MRCS(Edin),MCh(GASTRO)']
            self.departmentOptions = ['Anesthesiology', 'Bio-Chemistry', 'Cardiac Rehab Yoga', 'Cardio Thoracic Surgery', 'Cardiology', 'Chest Physician', 'Cosmetic Plastic and Hand Surgery', 'Critical Care', 'Dental&Facio maxillary Surgery', 'Dermatology', 'Diabetology', 'Dietary Services', 'Emergency Medicine', 'Endocrinology', 'Endoscopic,Head & Neck Surgery', 'Endoscopy', 'Gastroenterology', 'Gastrointestinal Medicine', 'General Medicine', 'General Surgery', 'Geriatrics', 'Gynecology', 'Hematology', 'Internal Medicine', 'Interventional Radiology', 'Laboratory Medicine', 'Laparoscopic Surgery', 'Medical Oncology', 'Micro-Biology', 'Nephrology', 'Neuro-Surgery', 'Neurology', 'Nuclear Medicine', 'Nuclear Medicinee', 'Obstetrics and Gynecology', 'Ophthalmology', 'Orthopedics & Traumatology', 'Otorhinolaryngology', 'Pathology', 'Pediatric Cardiology', 'Pediatric Surgery', 'Pediatrics', 'Physician', 'Physiotherapy', 'Psychiatry', 'Pulmonology', 'Radio-Diagnosis', 'Radiology', 'Rheumatology', 'Surgical Gastro-Enterology', 'Surgical Oncology', 'Urology', 'Vascular Surgery']
            self.doctor = doc;

            self.schedules = ko.observableArray(schedules);
            self.addSlot = function () {
                self.schedules.push(new Model.Schedule(null));
            };

            self.removeSlot = function () {
                console.log('removed');
                self.schedules.remove(this);
            }
        };
        var viewModel = new vm();
        ko.applyBindings(viewModel);
        $('#saveButton').click(function () {
            alert('savebutton');
            var testjson = ko.toJSON(pat);
            console.log(testjson);
            var formdata = new FormData();
            formdata.append("doctormetada", testjson);
            console.log(projectUrl + "updateDoctor");
            $.ajax({
                url: projectUrl + "updateDoctor",
                type: "POST",
                data: formdata,
                processData: false,
                contentType: false,
                success: function (res) {
                    formdata = new FormData();
                }
            });
        });

以下是 Demo