我有一個基本的HTML表單。我正在使用knockout.js來執行一些客戶端/服務器端操作。我可以很高興地添加或刪除聯繫人。提交值時我遇到了問題。當我點擊提交按鈕時,表單不會被重定向到任何地方。我相信這是由於self.save = function
。我該如何正確提交整個表單的值? JSFIDDLE表單不提交到服務器 - knockout.js
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));
你想達到什麼樣的?只保存值?在這種情況下,你可以只做一個ajax調用,並將lastSavedJson作爲參數發送到服務器的 –
@FlaviaObreja回到保存方法是的,我想只是點擊按鈕將值保存到服務器。我會怎麼做? –