何时使用(a)同步呼叫?

时间:2019-04-12 06:29:34

标签: javascript php ajax

我目前正在为我的办公室做一个小项目,作为一项学习练习。我们有一个传统,每个星期一都会带食物,所以我试图制作一个节目,显示每个人何时转。目前,我的网页能够创建带有备用栏的日历,用于显示用户的颜色。

(下面没有链接CSS文件的当前进度)

现在,我想为响应的用户分配一种颜色。我可以编写PHP方法,但是不确定如何将返回值放入字段中。当我尝试使用AJAX方法时,结果文本为“未定义”。因此,我读了一下,意识到AJAX函数是与其他进程并行执行的。

现在主要的问题是:我可以以某种方式使JavaScript等待变量返回之前,进一步扩展日历吗?还是应该在以后插入颜色。如果是这样:我该怎么办?

我不一定需要编写代码。一些解释或想法就足够了。

谢谢!

today = new Date();
currentMonth = today.getMonth();
currentYear = today.getFullYear();
currentWeek = getWeekNumber(today);
selectYear = document.getElementById("year");
selectMonth = document.getElementById("month");

months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];

monthAndYear = document.getElementById("monthAndYear");
showCalendar(currentMonth, currentYear);




function next() {
    currentYear = (currentMonth === 11) ? currentYear + 1 : currentYear;
    currentMonth = (currentMonth + 1) % 12;
    showCalendar(currentMonth, currentYear);
}

function previous() {
    currentYear = (currentMonth === 0) ? currentYear - 1 : currentYear;
    currentMonth = (currentMonth === 0) ? 11 : currentMonth - 1;
    showCalendar(currentMonth, currentYear);
}

function jump() {
    currentYear = parseInt(selectYear.value);
    currentMonth = parseInt(selectMonth.value);
    showCalendar(currentMonth, currentYear);
}


function showCalendar(month, year) {

    let firstDay = (new Date(year, month)).getDay();

    tbl = document.getElementById("calendar-body"); // body of the calendar

    // clearing all previous cells
    tbl.innerHTML = "";

    // filing data about month and in the page via DOM.
    monthAndYear.innerHTML = months[month] + " " + year;
    selectYear.value = year;
    selectMonth.value = month;

    // creating all cells



    let helper = 0;
    let dt = new Date(year,month,1);
    let date = (1+germanDate(dt.getDay()));

    // document.getElementById('dies').innerHTML = ((dt.getDay())+"<br />"+daysInMonth(month, year)+"<br />"+date);


    for (let i = 0; i < 6; i++) {
        // creates a table row
        let row = document.createElement("tr");

        //creating individual cells, filing them up with data.
            if (date > daysInMonth(month, year)) {
                if (helper<5){
                    while (helper<5){
                        let row = document.createElement("tr");
                        cell = document.createElement("td");
                        cell.classList.add("text-white");
                        cell.classList.add("bg-white");
                        cell.setAttribute('disabled', true);
                        cellText = document.createTextNode('|');
                        cell.appendChild(cellText);
                        row.appendChild(cell);
                        tbl.appendChild(row);
                        helper++;
                    }
                }
                break;
            }

            else {
                let dt = new Date(year,month,date)
                cell = document.createElement("td");

                    cellText = document.createTextNode(''+getWeekNumber(dt)+'. Week'); //insert weeknumber

                if (getWeekNumber(dt) === currentWeek && year === today.getFullYear() && month === today.getMonth()) {
                    cell.classList.add("table-info");   //if the week is the current one, make the cell blue
                } // color today's date
                cell.classList.add("cursorPointer");    //CSS -> change Cursor on hover
                cell.classList.add("col-11");

                cell.appendChild(cellText);
                row.appendChild(cell);

                cell = document.createElement("td");    //New cell for the color
                cellText = document.createTextNode('');
                cell.classList.add("col-1");
                cell.classList.add("table-white");
                cell.appendChild(cellText);
                row.appendChild(cell);


                date+=7;
                helper++;

            }

        tbl.appendChild(row); // appending each row into calendar body.
    }

}



var result = getWeekNumber(new Date());
document.write('It\'s currently week ' +result +'');


// check how many days in a month code from https://dzone.com/articles/determining-number-days-month
function daysInMonth(iMonth, iYear) {
    return 32 - new Date(iYear, iMonth, 32).getDate();
}

//By RobG https://stackoverflow.com/questions/6117814/get-week-of-year-in-javascript-like-in-php
function getWeekNumber(d) {
    // Copy date so don't modify original
    d = new Date(Date.UTC(d.getFullYear(), d.getMonth(), d.getDate()));
    // Set to nearest Thursday: current date + 4 - current day number
    // Make Sunday's day number 7
    d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay()||7));
    // Get first day of year
    var yearStart = new Date(Date.UTC(d.getUTCFullYear(),0,1));
    // Calculate full weeks to nearest Thursday
    var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7);
    // Return array of year and week number
    return weekNo;
}



function goToDetails(monat, jahr){
    window.open('?kalenderDetails&jahr='+jahr+'&woche='+monat);
}

function germanDate($datum){
    switch($datum){
        case 1: return 0;
        case 0: return 1;
        default: return (8-$datum);
    }
}
.table {
    border-collapse: collapse !important; }
    .table td,
    .table th {
      background-color: #fff !important; }

  .table-bordered th,
  .table-bordered td {
    border: 1px solid #dee2e6 !important; }

  .table-dark {
    color: inherit; }
    .table-dark th,
    .table-dark td,
    .table-dark thead th,
    .table-dark tbody + tbody {
      border-color: #dee2e6; }

  .table .thead-dark th {
    color: inherit;
    border-color: #dee2e6; } }

/*# sourceMappingURL=main.css.map */
<!DOCTYPE html>
<html lang="de">

<head>
    <meta charset="utf-8">


    <link rel="icon" href="as" id=icon>


    <script src="JavaScript/Icon.js"> </script>
</head>

<body style="min-height: 100%">


<div class='container-fluid' style='height: 100%'>
    <div class="row" style="margin-top: 2em">
                    <div class="container col-12 col-lg-6">
                            <div class="card">
                                <h3 class="card-header" id="monthAndYear"></h3>
                                <div class="table-responsive">
                                    <table class="table table-bordered table-hover" id="calendar">
                            
                                        <tbody id="calendar-body">
                            
                                        </tbody>
                                    </table>
                                </div>
                        
                                <div class="form-inline">
                        
                                    <button class="btn btn-outline-primary col-sm-6 rounded-0" id="previous" onclick="previous()">Previous</button>
                        
                                    <button class="btn btn-outline-primary col-sm-6 rounded-0" id="next" onclick="next()">Next</button>
                                </div>
                                <br/>
                                <form class="form-inline">
                                    <label class="col-sm-4 text-left" for="month">Jump To: </label>
                                    <select class="form-control col-sm-4 rounded-0" name="month" id="month" onchange="jump()">
                                        <option value=0>Jan</option>
                                        <option value=1>Feb</option>
                                        <option value=2>Mar</option>
                                        <option value=3>Apr</option>
                                        <option value=4>May</option>
                                        <option value=5>Jun</option>
                                        <option value=6>Jul</option>
                                        <option value=7>Aug</option>
                                        <option value=8>Sep</option>
                                        <option value=9>Oct</option>
                                        <option value=10>Nov</option>
                                        <option value=11>Dec</option>
                                    </select>
                        
                        
                                    <label for="year"></label><select class="form-control col-sm-4 rounded-0" name="year" id="year" onchange="jump()">
                                    <option value=2018>2018</option>
                                    <option value=2019>2019</option>
                                    <option value=2020>2020</option>
                                    <option value=2021>2021</option>
                                    <option value=2022>2022</option>
                                    <option value=2023>2023</option>
                                    <option value=2024>2024</option>
                                    <option value=2025>2025</option>
                                    <option value=2026>2026</option>
                                    <option value=2027>2027</option>
                                    <option value=2028>2028</option>
                                    <option value=2029>2029</option>
                                    <option value=2030>2030</option>
                                </select></form>
                            </div>

                            
        </div>
    </div>
</div>

        </body>
</html>

1 个答案:

答案 0 :(得分:0)

使用AJAX调用时,它会开始执行,但是其余代码不会在继续之前等待其完成,因此协调代码的执行会变得更加困难。

您需要做的是等待AJAX​​调用的响应。响应完成后,xmlHttpRequest对象将触发一个事件,因此您可以将事件侦听器附加到此事件,并在事件侦听器的回调内部触发需要等待AJAX​​调用完成的代码。

这在一开始可能会很棘手,但是一旦您了解了它的工作原理就很容易了,请记住,在javascript中某些代码可以同时执行,并且您需要通过回调协调不同的“线程”。

我强烈建议您阅读道格拉斯·克罗克福德(Douglas Crockford)的“ Javascript,好的部分”,这是一本最有见地的书,它了解这种语言上我们非常喜欢和讨厌的几个重要方面。