淘汰赛js和ajax

时间:2013-09-14 21:23:55

标签: jquery ajax knockout.js

我正在尝试使用从AJAX调用中检索到的一些信息来加载一个对象。 问题是,我似乎无法在屏幕上重新加载它,尽管代码没有显示错误。

我使用UserModel创建我的对象,然后,当AJAX成功响应时,我调用transform方法。我在document.onReady来电ko.applyBindings(new UserModel())

function transform(text){
    var user = JSON.parse(text);
    UserModel.firstName=user.firstName;
    UserModel.lastName=user.lastName;
    UserModel.email = user.email;
    var dateFormat=new Date(user.dob);
    var dateFormatted = dateFormat.getMonth()+1 + "/" + dateFormat.getDay() + "/" +     dateFormat.getFullYear();
    UserModel.dob = dateFormatted;
    UserModel.address1=user.address1;
    UserModel.address2=user.address2;
    UserModel.state=user.state;
    UserModel.city=user.city;
    UserModel.country=user.country;
}

function UserModel(){
    this.firstName=ko.observable("");
    this.lastName=ko.observable("");
    this.email=ko.observable("");
    this.dob=ko.observable("");
    this.address1=ko.observable("");
    this.address2=ko.observable("");
    this.country = ko.observable("");
    this.city=ko.observable("");
    this.state=ko.observable("");
}

感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

我建议你理解java脚本的原型。请看一下这段代码。 你必须先正确启动userModel。

function transform(text){
    var user = JSON.parse(text);
    userModel=new UserModel();
    userModel.firstName(user.firstName);
    userModel.lastName(user.lastName);
    userModel.email (user.email);
    var dateFormat=new Date(user.dob);
    var dateFormatted = dateFormat.getMonth()+1 + "/" + dateFormat.getDay() + "/" +     dateFormat.getFullYear();
    userModel.dob( dateFormatted);
    userModel.address1(user.address1);
    userModel.address2(user.address2);
    userModel.state(user.state);
    userModel.city(user.city);
    userModel.country(user.country);
    // now user userModel wherever you want like userModel.firstName()
}

function UserModel(){
    this.firstName=ko.observable("");
    this.lastName=ko.observable("");
    this.email=ko.observable("");
    this.dob=ko.observable("");
    this.address1=ko.observable("");
    this.address2=ko.observable("");
    this.country = ko.observable("");
    this.city=ko.observable("");
    this.state=ko.observable("");
}

答案 1 :(得分:-1)

这是很多重复自己。相反,只需这样做:

function UserModel (data) {
    var self = this;
    data = data || {};
    self.firstName = ko.observable(data.firstName);
    self.lastName = ko.observable(data.lastName);
    // and so on
}

然后只需使用JSON数据创建一个新的UserModel:

var user = new UserModel(JSON.parse(text));

无需转换功能。