后和补丁的重用功能在 JavaScript 中不起作用

问题描述

我是所有这些前端的新手,所以如果我没有正确解释这一点,请耐心等待。

我的页面包含带有 #btnAdd 添加按钮、.btnEdit 编辑按钮和 .btnDelete 删除按钮的数据表。
点击 #btnAdd.btnEdit 会打开一个模式 #exampleModal,我们可以在其中编辑和添加表单。

点击 #btnAdd POST 文档没有任何问题,同样点击 .btnEdit PATCH 文档没有任何问题。但是,如果我点击 btnAdd 和 POST 文档,然后继续编辑该文档,它不会PATCH而是POST

enter image description here

#btnAdd

// create operation
    $('#btnAdd').on('click',async function (e) {
        e.preventDefault();
        console.log('btnAddNew is clicked');

        // clearing forms
        // $("#menuSectionForm")[0].reset(); // clear form fields
        // $("#menuSectionForm").trigger('reset'); // clear form fields
        // document.getElementById('menuSectionForm').reset();  // clear form fields
        document.querySelector('#menuSectionForm').reset(); // clear form fields

        // clearing validator messages
        $('.fv-plugins-message-container').remove(); // remove message
        $('.is-invalid').removeClass('is-invalid'); // remove all invalid
        $('.is-valid').removeClass('is-valid'); // remove all valid

        // clearing fields
        $('#menuManagerSelect').val('');  // clearing select2

        // enabling disabling buttons
        $('#addMenuSectionFormSubmitButton').removeAttr('hidden','').removeAttr('disabled','disabled');  // show add button
        $('#updateMenuSectionFormSubmitButton').attr('hidden','').attr('disabled','disabled'); // hide update button

        // show modal
        const form = $('#exampleModal').modal('show');   // open modal

        // calling API Endpoint with validations feature
        const apiOptions = {
            method: 'post',url: `${HOST_URL}/api/v1/menu/section`,button: 'addMenuSectionFormSubmitButton'
        };

        _MenuSectionFormPush(apiOptions);
});

.btnEdit

// update operation
    $('#kt_datatable_2').on('click','.btnEdit',function (e) {
        e.preventDefault();
        console.log('btnEdit is clicked');

        var id = $(this).attr("aria-label");
        // console.log(id);

        // clearing validator messages
        $('.fv-plugins-message-container').remove(); // remove message
        $('.is-invalid').removeClass('is-invalid'); // remove all invalid
        $('.is-valid').removeClass('is-valid'); // remove all valid

        // clearing forms
        document.querySelector('#menuSectionForm').reset(); // clear form fields
        
        // clearing fields
        $('#menuManagerSelect').val('');    // clearing select2

        // enabling disabling buttons
        $('#addMenuSectionFormSubmitButton').attr('hidden','hidden').attr('disabled','disabled'); // hide add button
        $('#updateMenuSectionFormSubmitButton').removeAttr('hidden','disabled'); // show update button

        // show modal
        const form = $('#exampleModal').modal('show');   // open modal

        // retrieving data
        $.ajax({
            method: 'GET',url: `${HOST_URL}/api/v1/menu/section/${id}`,success: async function (raw) {
                console.log(raw);

                if (raw.status == 'success') {
                    // fetching menu manager select2
                    $.ajax({
                        method: 'GET',url: `${HOST_URL}/api/v1/menu/manager/popSel2/`+ raw.menuManager._id,dataType: 'json',}).then(function (data) {
                       
                        // updating menuManagerSelect values
                        var option = new Option(data.manager.text,data.manager.id,true,true);
                        $('#menuManagerSelect').append(option).trigger('change');
                    });

                    // updating fields with data
                    document.querySelector('#menuSectionId').value = raw.menuSection._id;
                    document.querySelector('#menuSectionName').value = raw.menuSection.name;
                    document.querySelector('#menuSectionDescription').value = raw.menuSection.description;
                    document.querySelector('#menuSectionPriority').value = raw.menuSection.priority;

                    // calling API Endpoint with validations feature
                    const apiOptions = {
                        method: 'patch',button: 'updateMenuSectionFormSubmitButton'
                    };

                    _MenuSectionFormPush(apiOptions);
                }
            },});

    });

重用发布和补丁的功能

    function _MenuSectionFormPush(apiOptions) {

    const apiURL = apiOptions.url;
    const apiMethod = apiOptions.method;
    const apiButton = apiOptions.button;

    // Getting Document related information
    const menuSectionForm = document.querySelector('#menuSectionForm');
    const FormSubmitButton = document.querySelector('#'+apiButton);
    const menuManagerSelect = document.querySelector('#menuManagerSelect');
    const menuSectionName = document.querySelector('#menuSectionName');
    const menuSectionDescription = document.querySelector('#menuSectionDescription');
    const menuSectionPriority = document.querySelector('#menuSectionPriority');

    // initialize
    // menuManagerSelect - Dropdown List : Single Select2
    $('#menuManagerSelect').select2({
        ajax: {
            url: `${HOST_URL}/api/v1/menu/manager/popSel2`,processResults: function (data) {
                return {
                results: data.manager
                };
            }
        },});

    // menuSectionPriority - Number : Number Controls Same Sides
    $('#menuSectionPriority').TouchSpin({
        buttondown_class: 'btn btn-secondary',buttonup_class: 'btn btn-secondary',verticalbuttons: true,verticalup: '<i class="ki ki-plus"></i>',verticaldown: '<i class="ki ki-minus"></i>',min: 1,max: 1000,step: 1,});

    // Return Form
    if (!menuSectionForm) {
    return;
    }

    // Validation
    fv = FormValidation.formValidation(menuSectionForm,{
        fields: {
            menuManagerSelect: {
                validators: {
                    notEmpty: {
                        message: 'Manager is required',},menuSectionName: {
                validators: {
                    notEmpty: {
                        message: 'Name cannot be empty',menuSectionDescription: {
                validators: {
                    notEmpty: {
                        message: 'Description cannot be empty',menuSectionPriority: {
                validators: {
                    notEmpty: {
                        message: 'This field is required',plugins: {
            //Learn more: https://formvalidation.io/guide/plugins
            trigger: new FormValidation.plugins.Trigger(),// Bootstrap Framework Integration
            bootstrap: new FormValidation.plugins.Bootstrap(),// Validate fields when clicking the Submit button
            FormSubmitButton: new FormValidation.plugins.SubmitButton(),// Submit the form when all fields are valid
            //defaultSubmit: new FormValidation.plugins.DefaultSubmit(),});
            
    // validation successful
    const validFunction = fv.on('core.form.valid',async function () {

        if (!isLoading) {
            isLoading = true;
                
            // Show loading state on button
            KTUtil.btnWait(FormSubmitButton,_buttonSpinnerClasses,'Please wait');

            // Accessing Restful API
            await axios({
                method: apiMethod,url: apiURL,data: {
                    manager: document.querySelector('#menuManagerSelect').value,name: document.querySelector('#menuSectionName').value,description: document.querySelector('#menuSectionDescription').value,priority: document.querySelector('#menuSectionPriority').value,}).then(function (res) {
            
                // Return valid JSON
                // console.log(res);

                // Release button
                KTUtil.btnRelease(FormSubmitButton);

                // TOASTR EXAMPLE
                toastr.options = {
                    "closeButton": false,"debug": false,"newestOnTop": true,"progressBar": false,"positionClass": "toast-top-right","preventDuplicates": false,"onclick": null,"showDuration": "300","hideDuration": "1000","timeOut": "5000","extendedTimeOut": "1000","showEasing": "swing","hideEasing": "linear","showMethod": "fadeIn","hideMethod": "fadeOut"
                };

                if (res.data.status == 'success') {
                    // reseting & clearing
                    $('#exampleModal').modal('hide')  // hiding modal form
                    toastr.success(`${res.data.message}`,`${res.data.status}`); // show sucess toastr
                    $('#kt_datatable_2').KTDatatable().reload(); // reload table
                    isLoading = false;

                }
                else if (res.data.status == 'error') {
                    $('#exampleModal').modal('hide')  // hiding modal form
                    toastr.error(`${res.data.message}`,`${res.data.status}`)
                    isLoading = false;

                }
                else {
                    $('#exampleModal').modal('hide')
                    isLoading = false;
                };
            });
        }
    });

    // validation failed
    const invalidFunction  = fv.on('core.form.invalid',function () {
                console.log('Something went wrong!!');
                isLoading = false;
    });

    return isLoading;
};

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)