我目前正在学习knockout.js及其独特的功能。我已成功创建了联系表单。我可以根据需要添加或删除尽可能多的联系人。我不太了解将值存储在数据库中的概念。我将值放在JSON对象中,然后使用$.post("/some/url.php"
发送mysql db中的存储值。但是,根本不工作。我在服务器端使用php。如何在mysql db中存储联系人值?我还需要将json对象解码为php中的普通数组进行存储吗? JSFIDDLE
var initialData = [{
firstName: "Jenny",
lastName: "LaRusso",
phone: "(555) 121-2121",
alt_phone: "(555) 123-4567",
main1: false,
main2: true
}, {
firstName: "Sensei",
lastName: "Miyagi",
phone: "(555) 444-2222",
alt_phone: "(555) 999-1212",
main1: true,
main2: false
}];
var ContactsModel = function (contacts) {
var self = this;
self.contacts = ko.observableArray([]);
ko.utils.arrayForEach(contacts, function (contact) {
self.contacts.push({
firstName: contact.firstName,
lastName: contact.lastName,
phone: contact.phone,
alt_phone: contact.alt_phone,
main1: ko.observable(contact.main1),
main2: ko.observable(contact.main2)
});
});
self.addContact = function () {
self.contacts.push({
firstName: "",
lastName: "",
phone: "",
alt_phone: "",
main1: false,
main2: false
});
};
self.removeContact = function (contact) {
self.contacts.remove(contact);
};
self.addPhone = function (contact) {
contact.phones.push({
number: ""
});
};
self.removePhone = function (phone) {
$.each(self.contacts(), function () {
this.phones.remove(phone)
})
};
self.save = function () {
self.lastSavedJson(JSON.stringify(ko.toJS(self.contacts), null, 2));
};
self.lastSavedJson = ko.observable("");
//This is not working
$.post("/some/url.php", initialData, function(returnedData) {
// This callback is executed if the post was successful
})
};
ko.applyBindings(new ContactsModel(initialData));
答案 0 :(得分:1)
你的小提琴不起作用,因为它没有引用jQuery。也许那是你的问题。这里有一个小提琴:http://jsfiddle.net/azurelogic/dLbY7/17/。现在我得到一个404,因为" /some/url.php"不是真的。
编辑:
逻辑也关闭了。您应该在save函数之前声明lastSavedJson。此外,需要在保存内部调用帖子。像这样:
self.lastSavedJson = ko.observable("");
self.save = function () {
self.lastSavedJson(JSON.stringify(ko.toJS(self.contacts), null, 2));
$.post("/some/url.php", self.lastSavedJson(), function(returnedData) {
// This callback is executed if the post was successful
})
};
//initial post if it is still needed
$.post("/some/url.php", initialData, function(returnedData) {
// This callback is executed if the post was successful
})
如果你真的不需要将lastSavedJson用于其他任何事情,你可以将其内联到帖子中。
我发现如果我首先声明所有可观察量,然后计算,最后是函数,这会有所帮助。