使用AJAX进行jquery更改功能

时间:2017-02-07 10:23:06

标签: jquery ajax

我使用API​​来显示根据月份的祷告时间,我想在我加载页面时显示当前的月祷告时间,我的代码在下面给出。我可以在页面加载时显示当前的月祷告时间。

$(document).ready(function() {
    $('.months').change(function() {
        var $month = $('.months').val();
        var d = new Date();
        var curr_year = d.getFullYear();
        var $monthText = $(".months option:selected").text();
        $('#selected-month').html('Prayer Timings For '+ $monthText);
        function splitTime(time) {
            return time.split(" ", 1);
        }
        $.ajax({
            method: 'GET',
            url: 'https://api.aladhan.com/calendarByCity?city=Hyderabad\
            &country=IN&month=' + $month + '&year=' + curr_year + '&method=2&school=1',
            success: function(data) {
                var rowCount = $('#myTable >tbody >tr').length;
                if (rowCount > 0) {
                    $("#myTable > tbody > tr").remove();
                }
                $.each(data.data, function(i, v) {
                    var timing = v.timings;
                    $('#myTable > tbody:last-child').append('<tr>\
                                         <th>' + v.date.readable + '</th>\
                                         <th>' + splitTime(timing.Fajr) + '</th>\
                                         <th>' + splitTime(timing.Sunrise) + '</th>\
                                         <th>' + splitTime(timing.Dhuhr) + '</th>\
                                         <th>' + splitTime(timing.Asr) + '</th>\
                                         <th>' + splitTime(timing.Maghrib) + '</th>\
                                         <th>' + splitTime(timing.Isha) + '</th>\
                                         </tr>');

                })
            },
            error: function(data) {
                alert('There is no response from server side');
            }
        });
    })
 <form>
   <select class="form-control months">
       <option>Select Month</option>
       <option value="01">January</option>
       <option value="02">February</option>
       <option value="03">March</option>
       <option value="04">April</option>
       <option value="05">May</option>
       <option value="06">June</option>
       <option value="07">July</option>
       <option value="08">August</option>
       <option value="09">September</option>
       <option value="10">October</option>
       <option value="11">November</option>
       <option value="12">December</option>
     </select>
</form>

1 个答案:

答案 0 :(得分:0)

当页面加载时,您可以将下拉列表设置为当前月份,然后触发更改事件。

JSFiddle

//Date.getMonth returns 0-11

var month = new Date().getMonth() + 1;
if (month < 10) {
    month = "0" + month;
}
$('.months').val(month).trigger("change");

将其放在$(document).Ready()

的末尾