【发布时间】:2019-01-27 20:00:46
【问题描述】:
我尝试了很多组合,但我无法处理。 我有一个带有 knockout.js 绑定的表单。我需要使一个对象由表单中的值组成,然后通过 ajax() 请求将此对象发送到服务器。我完全迷路了,不知道如何继续...请您帮我正确创建对象吗?
当我尝试一个干净的工作区时,我抹去了我的尝试。
我的表格:
<form data-bind="submit: AddService">
Name: <input data-bind="value: serviceName" /><br />
Address: <input data-bind="value: serviceAddress" /><br />
Interval:<select data-bind="options: $root.availableIntervals,value: 'selectedInterval', optionsText: 'interval'"></select><br />
Notifications: <input type="checkbox" data-bind="checked: wantNotification" /><br />
<button type="submit">Save</button>
</form>
我的 JS:
<script>
function ServiceToSend(serviceName, serviceAddress, notifications, selectedInterval) {
self.name = ko.observable(serviceName);
self.address = ko.observable(serviceAddress);
self.notifications = ko.observable(notifications);
self.checkInterval = ko.observable(selectedInterval);
} //This is the function to make object that I tried.
function ServicesViewModel() {
var self = this;
self.availableIntervals = [
{ interval: "1", value: 1 },
{ interval: "2", value: 2 },
{ interval: "3", value: 3 }
];
serviceName = ko.observable();
serviceAddress = ko.observable();
wantNotification = ko.observable(false);
selectedInterval = ko.observable();
self.AddService = function () {
$.ajax({
type: "POST",
url: "http://localhost:55972/api/services/add/",
data: {
//I Need object here consist of form elements.
},
}).done(function (msg) {
});
};
};
ko.applyBindings(new ServicesViewModel());
我不知道在哪里以及如何调用 new SendServiceToSend()。每次我尝试调用它时,在 console.log() 显示它后,我都会得到 undefined 或一些奇怪的 *string。
【问题讨论】:
标签: javascript html ajax forms knockout.js