在knockout中通过ajax绑定select

binding select via ajax in knockout

本文关键字:ajax 绑定 select knockout      更新时间:2023-09-26

我有一个发送到远程API的表单。表单工作正常,但我需要用Ajax调用填充选择框中的选项。

这是我到目前为止所知道的,但对下一步一无所知。

form.html

<form data-bind="submit: mySubmit" role="form">
    <select data-bind="
        options: operative,
        optionsValue: 'id',
        optionsText: function(i) {
            return i.FirstName + ' ' + i.LastName
        },
        optionsCaption: 'Choose...'
    "></select>
    <select data-bind="
        options: claim,
        optionsValue: 'id',
        optionsText: function(i) {
            return i.id
        },
        optionsCaption: 'Choose...'
    "></select>
    <textarea data-bind="value: body" cols="23" rows="5"></textarea>
    <input data-bind="value: entryDate" type="text">
    <button type="submit">Go</button>
</form>
javascript

var viewModel = {
    operative: ko.observable(),
    claim: ko.observable(),
    body: ko.observable(),
    entryDate: ko.observable(),
    operative: [{}],
    claims: [{}],
    mySubmit : function(formElement) {
        var formData = {
            'operative' : viewModel.firstname() ,
            'claim'  : viewModel.lastname(),
            'body' : viewModel.firstname() ,
            'entryDate'  : viewModel.lastname()
        };
        console.log(formData)
        $.ajax({
            url: '/api/entry/',
            type: "POST",
            data: JSON.stringify(formData),
            datatype: "json",
            processData:false,
            contentType: "application/json; charset=utf-8",
            success: function (result){
                alert("success");
            }
        });
    }
};
ko.applyBindings(viewModel);

我需要用Ajax调用填充选择框中的选项。

好吧,让它们可观察(即ko.observableArray()),发出Ajax请求并在它们返回时填充它们。

(我对你的代码做了一些细微的修改,请仔细阅读。)

var viewModel = {
    operatives: ko.observableArray(),
    claims: ko.observableArray(),
    body: ko.observable(),
    entryDate: ko.observable(),
    selectedOperative: ko.observable(),
    selectedClaim: ko.observable(),
    submit: function () {
        $.post('/api/entry/', {
            operative: this.selectedOperative(),
            claim: this.selectedClaim(),
            body: this.body(),
            entryDate: this.entryDate()
        }, 'json').done(function (result){
            console.log('submit success', result);
        });
    }
};
$.get('/api/operatives/').done(viewModel.operatives);
$.get('/api/claims/').done(viewModel.claims);
ko.applyBindings(viewModel);

<form data-bind="submit: submit" role="form">
    <select data-bind="
        value: selectedOperative,
        options: operatives,
        optionsValue: 'id',
        optionsText: function(i) {
            return i.FirstName + ' ' + i.LastName
        },
        optionsCaption: 'Choose...'
    "></select>
    <select data-bind="
        value: selectedClaim,
        options: claims,
        optionsValue: 'id',
        optionsText: id
        optionsCaption: 'Choose...'
    "></select>
    <textarea data-bind="value: body" cols="23" rows="5"></textarea>
    <input data-bind="value: entryDate" type="text">
    <button type="submit">Go</button>
</form>

注意:

$.get('/api/operatives/').done(viewModel.operatives);

等价于:

$.get('/api/operatives/').done(function (result) {
    viewModel.operatives(result);
});

当然这取决于你的API íf你可以使用这个小快捷方式

您需要声明一个可观察数组,然后立即调用ajax端点(此代码段假设您的ajax结果不需要任何处理来用作选项):

myOptions: ko.observableArray(),
$.ajax({
        url: '/api/optionsUrl/',
        type: "GET",
        datatype: "json",
        processData:false,
        contentType: "application/json; charset=utf-8",
        success: function (result){
            myOptions(result);
        }
    });

然后你可以在你的html:

中设置这些选项
<select data-bind="
    options: myOptions,
    optionsValue: 'id',
    optionsText: function(i) {
        return i.id
    },
    optionsCaption: 'Choose...'
"></select>