简体   繁体   English

从ajax调用返回html并格式化

[英]Return html from ajax call and format it

According to my scenario in my laravel project, A customer can select a date from datepicker.根据我在 laravel 项目中的场景,客户可以从 datepicker 中选择一个日期。 according to the selected date, available times will be display to the customer.根据选择的日期,将向客户显示可用时间。 I used Ajax to send the selected date to the database, the controller select all available times from database and send back as ajax success data.我使用 Ajax 将选定的日期发送到数据库,控制器从数据库中选择所有可用时间并作为 ajax 成功数据发回。 I hard coded the all time slots as bootstrap radio button group to show the times to customer.我将所有时间段硬编码为引导单选按钮组,以向客户显示时间。 I want to disable the buttons with ajax returned times among the button group.我想禁用按钮组中带有 ajax 返回次数的按钮。 how can I change the status of the buttons to disable according to ajax return data.如何根据ajax返回数据更改按钮的状态以禁用。 how can I format the html with javascript to perform this?如何使用 javascript 格式化 html 以执行此操作?

Datepicker and hard coded button group with time slots.日期选择器和带有时隙的硬编码按钮组。 在此处输入图片说明

Ajax returned times, according to selected date (console log output) Ajax 返回次数,根据选择的日期(控制台日志输出) 在此处输入图片说明

Ajax code I have used我使用过的 Ajax 代码

const $datepicker = $('#date').datepicker({
    format: 'yyyy-mm-dd'
});

$datepicker.on('changeDate', function (e) {
    $.ajax({
        type: "POST",
        url: '/process_date',
        data: {
            date: convert(e.date.toString()),
        },
        success: function (result) {
            console.log(result);
        },
        error: function (error) {
            console.log(error);
        }
    });

    function convert(str) {
        var date = new Date(str),
            month = ("0" + (date.getMonth() + 1)).slice(-2),
            day = ("0" + date.getDate()).slice(-2);
        return [date.getFullYear(), month, day].join("-");
    }
});

As API is returning Date object, first you have to process Date to convert it into time format of 12 Hours, please use formatDateToTime to get the correct time, and then you use this value to enable disable radio buttons:由于 API 正在返回Date对象,首先您必须处理Date将其转换为 12 小时的时间格式,请使用formatDateToTime获取正确的时间,然后使用此值启用禁用单选按钮:

 function formatDateToTime(date) { var hours = date.getHours(); var minutes = date.getMinutes(); var ampm = hours >= 12 ? 'pm' : 'am'; hours = hours % 12; hours = hours ? hours : 12; // the hour '0' should be '12' minutes = minutes < 10 ? '0'+minutes : minutes; var strTime = hours + ':' + minutes + ' ' + ampm; return strTime; } var dt = new Date( "December 25, 1995 23:15:20" ); console.log(formatDateToTime(dt));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM