【问题标题】:How to make object for ajax request from knockout form?如何从淘汰表单中为 ajax 请求制作对象?
【发布时间】: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


    【解决方案1】:

    Knockout 在submit binding 上为您传递formElement。因此,您只需将参数添加到AddService() 函数即可开始使用它。然后可以使用jQuerysserialize()将表单元素转换为ajax请求可以使用的url编码字符串。

    KO 将表单元素作为参数传递给您的提交处理函数。如果需要,您可以忽略该参数,或者您可能希望以多种方式使用它,例如:

    例如,您不需要ServiceToSend(),而是可以执行以下操作:

    self.AddService = function (formElement) {
        $.ajax({
            type: "POST",
            url: "http://localhost:55972/api/services/add/",
            data: $( formElement ).serialize(),
        }).done(function (msg) {
        });
    };
    

    一个半相关的小说明:默认情况下,Knockout 不会提交表单,因此您不必担心会阻止 HTML 表单的默认操作,即实际提交到服务器。

    当您在表单上使用提交绑定时,Knockout 将阻止浏览器对该表单的默认提交操作。

    【讨论】:

    • 我按照你说的尝试过,我希望这是正确的参数:(serviceName,serviceAddress,wantNotification,selectedInterval)但它仍然添加具有空值的服务:{“serviceId”:4171,“name ":null,"address":null,"notifications":false,"checkInterval":0,"checks":null,"lastCheck":"0001-01-01T00:00:00"}]
    • “我希望这是正确的参数:”是什么意思?您是否完全按照我的答案尝试过?
    • 是的,我在添加评论后几秒钟就恢复了它。:D 我完全按照你写的方式尝试了它,但仍然是空值。 :( 我也试图通过以下方式显示这里发生了什么: serviceName = $(formElement).serialize(); console.log(serviceName); 它什么也不显示。
    • 我会仔细检查您是如何创建表单的。
    • 双重检查?就像只是看代码并尝试找到我做错的地方还是它的一些功能? :D 我是初学者,很抱歉我的粗鲁。 :|我有一个使用点击绑定 insted 提交的想法,但我不知道它是否会给我输入值..
    【解决方案2】:

    serviceName 不是您的 ServicesViewModel() 的一部分,请尝试:

    self.serviceName = ko.observable();
    self.serviceAddress = ko.observable();
    self.wantNotification = ko.observable(false);
    self.selectedInterval = ko.observable();
    

    在 AddService 中调用 ko.toJSON

    self.AddService = function () {
        var dataToSend = ko.toJson(self)
        $.ajax({
            type: "POST",
            url: "http://localhost:55972/api/services/add/",
            data: dataToSend,
        }).done(function (msg) {
        });
    };
    

    注意:dataToSend 将包含视图模型中的所有数据。这可能不是您想要的。要仅发送表单数据,请创建一个仅包含表单数据的新对象。在表单上使用'with' 数据绑定。使用该对象调用 ko.toJSON。这是jsFiddle

    【讨论】:

    • 这很好,但它不会添加具有价值的服务。 :( 它运作良好,但看起来我不需要发送 json。这是 Andrew 解决方案中的格式,它添加没有问题:name=dad&address=dada&checkInterval=1&notifications=true 有没有办法制作这种格式with ko?我想使用淘汰赛形式,所以如果可以的话,那就太好了。
    • 您可以使用淘汰赛。如果您不希望 JSON 像您的问题所述,也许重新提出问题。您还可以转换数据。 "name=" + data.name + "&address=" + data.address
    猜你喜欢
    • 1970-01-01
    • 2013-03-09
    • 2016-04-28
    • 2014-01-21
    • 1970-01-01
    • 2012-11-02
    • 2017-09-10
    • 2013-03-12
    • 1970-01-01
    相关资源
    最近更新 更多