通过knockout数据绑定获取输入字段中的值

时间:2014-05-03 11:29:20

标签: javascript knockout.js knockout-2.0

我从表单字段获取输入字段的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(idValue);
    this.name = ko.observable(nameValue);
    this.degree = ko.observable(degreeValue);
    this.gender = ko.observable(genderValue);
    //this.consultant= ko.observableArray(consultantArrValue);
    this.username = ko.observable(usernameValue);
    this.password = ko.observable(passwordValue);
    this.email = ko.observable(emailValue);
    this.mobile = ko.observable(mobileValue);    
    this.imgFile = ko.observable(imgFileValue);
    this.imgSrc = ko.observable(imgSrcValue);
    this.imagePath=ko.observable(imagePathValue); 
    this.userid=ko.observable(useridValue); 
    this.department=ko.observable(departmentValue);
    //this.consultant= ko.observableArray(consultantArrValue);
    //this.consultant= ko.observable(consultantValue);
    this.addSlot=function(doctor)
{


     var docSchedule=new DocSchedule();
     iter=iter+1;
     docSchedule.id(iter);
     doctor.schedules.push(docSchedule);
}


}

//idValue = 'hi';
//useridValue = 'hi';
//nameValue = 'hi';
addressValue = 'adress';
//genderValue = 'hi';
//mobileValue = 'hi';
//these fields are not available
//usernameValue = 'hi';
//passwordValue = 'hi';
//emailValue = 'hi';
imgFileValue = 'imagefileValue';
//imgSrcValue = 'ui_resources/img/profile_pic.png';
imagePathValue = 'imagePathValue';
//consultantArrValue = null;//'${currentpatient.user.name}';
//consultantValue="d1";
//var doc={};
var projectUrl=$('#projectUrl').val();

//alert(projectUrl);
/* var test=$.ajax({  
    type: "GET", 
    url: projectUrl+"getDoctors",  
    dataType:"json",
    jsonp: true,
    async:false 
}).responseText;
console.log(test); */
$.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); 
           nameValue = currPat.name;
           usernameValue =currPat.username;
           passwordValue ="" ;
           emailValue = currPat.email;
           mobileValue = currPat.mobile;
           genderValue = currPat.gender;
           departmentValue=currPat.department;
           degreeValue=currPat.degree;
           imgSrcValue=currPat.imagePath;
           useridValue=currPat.userid;
           idValue=currPat.id;
            }
       });    
      }
});
/* 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);
$('#saveButton').click(function(){
    alert('savebutton');
    var testjson=ko.toJSON(patp);
    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());
                }

        });

});

查看此answer

将我的代码更改为

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(idValue);
    this.name = ko.observable(nameValue);
    this.degree = ko.observable(degreeValue);
    this.gender = ko.observable(genderValue);
    //this.consultant= ko.observableArray(consultantArrValue);
    this.username = ko.observable(usernameValue);
    this.password = ko.observable(passwordValue);
    this.email = ko.observable(emailValue);
    this.mobile = ko.observable(mobileValue);    
    this.imgFile = ko.observable(imgFileValue);
    this.imgSrc = ko.observable(imgSrcValue);
    this.imagePath=ko.observable(imagePathValue); 
    this.userid=ko.observable(useridValue); 
    this.department=ko.observable(departmentValue);
    //this.consultant= ko.observableArray(consultantArrValue);
    //this.consultant= ko.observable(consultantValue);
    this.addSlot=function(doctor)
{


        mm = doctor
        console.log("this", doctor);
        var docSchedule = new DocSchedule();
        iter++;
        docSchedule.id(iter);
        this.schedulers().push(docSchedule);
}


}

//idValue = 'hi';
//useridValue = 'hi';
//nameValue = 'hi';
addressValue = 'adress';
//genderValue = 'hi';
//mobileValue = 'hi';
//these fields are not available
//usernameValue = 'hi';
//passwordValue = 'hi';
//emailValue = 'hi';
imgFileValue = 'imagefileValue';
//imgSrcValue = 'ui_resources/img/profile_pic.png';
imagePathValue = 'imagePathValue';
//consultantArrValue = null;//'${currentpatient.user.name}';
//consultantValue="d1";
//var doc={};
var projectUrl=$('#projectUrl').val();

//alert(projectUrl);
/* var test=$.ajax({  
    type: "GET", 
    url: projectUrl+"getDoctors",  
    dataType:"json",
    jsonp: true,
    async:false 
}).responseText;
console.log(test); */
$.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); 
           nameValue = currPat.name;
           usernameValue =currPat.username;
           passwordValue ="" ;
           emailValue = currPat.email;
           mobileValue = currPat.mobile;
           genderValue = currPat.gender;
           departmentValue=currPat.department;
           degreeValue=currPat.degree;
           imgSrcValue=currPat.imagePath;
           useridValue=currPat.userid;
           idValue=currPat.id;
            }
       });    
      }
});
/* 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.person = new Patientp();
            self.schedule = new DocSchedule();
            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, document.getElementById('addDoctorSchedules'));
$('#saveButton').click(function(){
    alert('savebutton');
    var testjson=ko.toJSON(self.person);
    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());
                }

        });

});

所以现在我没有在表单字段中获取任何值,甚至在浏览器控制台中也没有错误。

enter image description here

任何人都可以指出我正在做的错误吗?

2 个答案:

答案 0 :(得分:1)

这是因为从ajax请求到viewmodel Patientp的数据初始化,

尝试将Patientp更改为此。

HTML

<table id="test">
    <tr>
        <td>Name</td>
        <td><input type="text" name="name" data-bind='value: person.name' /></td>
    </tr>
    <tr>
        <td>Department</td>
        <td><select data-bind='options: departmentOptions, optionsText: departmentOptions, optionsCaption: "Select...", value: person.department'> </select></td>
    </tr>
    <tr>
        <td>Gender</td>
        <td><select data-bind='options: genderOptions, optionsText: genderOptions, optionsCaption: "Select...", value: person.gender'> </select></td>
    </tr>
    <tr>
        <td>Degree</td>
        <td><select data-bind='options: degreeOptions, optionsText: degreeOptions, optionsCaption: "Select...", value: person.degree'> </select></td>
    </tr>
    <tr>
        <td>UserName</td>
        <td><input type="text" name="name" data-bind='value: person.username' /></td>
    </tr>
    <tr>
        <td>Password</td>
        <td><input type="text" name="name" data-bind='value: person.password' /></td>
    </tr>
</table>

的javaScript

var Patientp = function () {
    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('');
}

然后设置如下值:

if (currPat.userid == "${IDis}") {
    console.log(currPat.degree);
    pat.name = currPat.name;
    pat.username = currPat.username;
    pat.password = currPat.password;
    pat.email = currPat.email;
    pat.mobile = currPat.mobile;
    pat.gender = currPat.gender;
    pat.department = currPat.department;
    pat.degree = currPat.degree;
    pat.imagePath = currPat.imagePath;
    pat.userid = currPat.userid;
    pat.id = currPat.id;
}

这里是 Demo

答案 1 :(得分:0)

没有html文件很难理解你的连接所以我只能提供一个简单的例子来说明如何完成连接:

HTML

<form id="cInfo" data-bind="with: $root.dataToShow">
<input  data-bind="value: username">
<input  data-bind="value: department">
<input  data-bind="value: gender">
...
</form>

JS

var myModel = new MyViewModel();

$(document).ready(function (e) {
ko.applyBindings(myModel);
});
function MyViewModel(){
var self=this;
self.dataToShow=ko.observable();
$.ajax({
    type: "GET", 
    url: url,  
    dataType:"json",
    jsonp: true,
    async:false ,
    success: function (data) {
         self.dataToShow(data); /// data:  {username:"", department:"", gender:""}
    }
});

}