douwan2664 2014-07-29 10:53
浏览 74
已采纳

为什么AJAX不能用于for循环

I am working on small application which is supposed to generate working schedules and count hours: http://www.ankieta.gorna.pl/kalendarz.php. I wrote the function kalkulacja() which is supposed to count each row's inputs and output results via ajax. I can't figure out why it does only the last row, throwing error in all previous cases. I would appreciate your help.

<body onload="init();">
    <div class="container">
            <button type="button" id="tydz_minus" name="tydz_minus"><</button>
            <button type="button" id="tydz_plus" name="tydz_plus">></button>
        <table id="tabela">
            <thead>
                <tr>
                    <td></td>
                    <td class="tydz" id="pon"></td>
                    <td class="tydz" id="wt"></td>
                    <td class="tydz" id="sr"></td>
                    <td class="tydz" id="czw"></td>
                    <td class="tydz" id="pn"></td>
                    <td class="tydz" id="sob"></td>
                    <td class="tydz" id="ndz"></td>
                    <td>tydz.</td>
                    <td>miesiąc</td>
                </tr>
            </thead>
            <tbody id="tbody">
                <?php
                    $dane = $_POST["staff"];
                    $link = mysqli_connect("") or die("Error " . mysqli_error($link));

                    if($link) {
                        echo "";
                    } else {
                        echo "nie ok";
                    }
                    $result = mysqli_query($link,"SELECT staff FROM Staff");
                    while($row = mysqli_fetch_array($result)) {
                    $pracownik = $row['staff'];
                    print "<tr><td>" . $pracownik . "</td><td><input id='time' type='text'><input id='time' type='text'></td><td><input id='time' type='text'><input id='time' type='text'></td><td><input id='time' type='text'><input id='time' type='text'></td><td><input id='time' type='text'><input id='time' type='text'></td><td><input id='time' type='text'><input id='time' type='text'></td><td><input id='time' type='text'><input id='time' type='text'></td><td><input id='time' type='text'><input id='time' type='text'></td><td id='ww'></td><td></td></tr>";
                    }
                ?>
            </tbody>
        </table>        
            <input name="staff" id="staff" type="text"/>
            <input type="submit" value="Dodaj pracownika" onclick="save_staff();"/>
    </div>
        <script>
        $(document).ready(function() {
        $('#tbody tr td #time').datetimepicker({
        datepicker:false,
        format:'H:i'
        }); });
    </script>
</body>



function init() {
    var zlap_plus = document.getElementById("tydz_plus");
    var zlap_minus = document.getElementById("tydz_minus");
    zlap_plus.onclick = plus_tydz;
    zlap_minus.onclick = minus_tydz;
    dni();
    for(var e = 0 ; e < 19 ; e++) {
    kalkulacja(e); }
}
var dzis = new Date();
var day = 86400000;
var pon = Date.now() - ((dzis.getDay()*day)-day);                       //zwraca pierwszy dzień tygodnia
var pierwszy = Date.now() - ((dzis.getDate() - dzis.getDay())*day);     //zwraca pierwszy dzień miesiąca
//Funkcja tworzy nagłówek tabeli i generuje daty
function dni() {
                document.getElementById("pon").innerHTML = "<div id='cell'>" + new Date(pon).toLocaleDateString() + "</div>";
                document.getElementById("wt").innerHTML = new Date(pon + day).toLocaleDateString();
                document.getElementById("sr").innerHTML = new Date(pon + (2*day)).toLocaleDateString();
                document.getElementById("czw").innerHTML = new Date(pon + (3*day)).toLocaleDateString();
                document.getElementById("pn").innerHTML = new Date(pon + (4*day)).toLocaleDateString();
                document.getElementById("sob").innerHTML = new Date(pon + (5*day)).toLocaleDateString();
                document.getElementById("ndz").innerHTML = new Date(pon + (6*day)).toLocaleDateString();
}
//Funkcja przesuwa kalendarz o tydzień
function plus_tydz() {
                pon = pon+7*day;
                return dni();

            }
//Funkcja cofa kalendarz o tydzień
function minus_tydz() {
                pon = pon-7*day;
                return dni();

            }
//Funkcja tworzy nowy obiekt ajax
var ajax = createXmlHttpRequestObject();
function createXmlHttpRequestObject() {
            var ajax;

            if(window.ActiveXObject) {
                try {
                    ajax = new ActiveXObject("Microsoft.XMLHTTP");
                } catch(e) {
                    ajax = false;
                }
            }
            else {
                try {
                    ajax = new XMLHttpRequest();
                } catch(e) {
                    ajax = false;
                }
            }
            if (!ajax) 
                alert("Nie uadło się utworzyc obiektu");
            else 
            return ajax;
    } 
//Funkcja zapisuje w bazie danych nowego pracownika via ajax
function save_staff() {
    if(ajax) {
        var staff = document.getElementById("staff").value;
        var dane = "staff=" + staff;
        ajax.open("POST", "kalendarz_dane.php", true);
        ajax.onreadystatechange = handle;
        ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        ajax.send(dane);
    }

}
//Funkcja obsługuje odpowiedź serwera z funkcji save_staff
function handle() {
        if(ajax.readyState == 4) {
            if(ajax.status == 200) {
                try {
                    document.getElementById("tbody").innerHTML = ajax.responseText;
                }catch(e) {
                    alert(e.toString());
                }
            } else {
                alert(ajax.statusText);
            }
        }
    }
function kalkulacja(e) {
    var cal = 0;
    var len = document.getElementById("tbody").rows.length;
    for(var i = 1 ; i < 8 ; i++) {
        var x = document.getElementById("tbody").rows[e].cells[i].children[0].value;
        var y = document.getElementById("tbody").rows[e].cells[i].children[1].value;
        var timeStart = new Date("01/09/1970 " + x).getTime();
        var timeEnd = new Date("01/09/1970 " + y).getTime();
        var workday = (timeEnd - timeStart) / 3600000;
        cal += workday; }
    if(ajax) {
        var mk = "cal=" + cal;
        ajax.open("GET", "kalendarz_time.php?cal=" + cal, true);
        ajax.onreadystatechange = handletime;
        ajax.send(null);
    } else {
        setTimeout(kalkulacja(e), 2000)
    }
    function handletime() {
        if(ajax.readyState == 4) {
            if(ajax.status == 200) {
                try {
                    var s = 8 + (e*10)
                    document.getElementById("tbody").getElementsByTagName("td").item(s).innerHTML = ajax.responseText;
                    setTimeout(kalkulacja(e), 2000);
                }catch(e) {
                    alert(e.toString());
                }
            } else {
                alert(ajax.statusText);
            }
        }
    }

}
  • 写回答

1条回答 默认 最新

  • doulei3488 2014-07-29 11:07
    关注

    This line:

    setTimeout(kalkulacja(e), 2000)
    

    should be:

    setTimeout(function() {
        kalkulacja(e);
    }, 2000);
    

    The way you've written it, it's calling kalkulacja when you set the timeout, not when the timer expires.

    The main problem, though, is that you're using the same ajax object every time you call kalkulacja. If you make multiple concurrent AJAX calls, you need to use a different XMLHttpRequest objects for each of them. So kalkulakja should begin with:

    var ajax = createXmlHttpRequestObject();
    

    so you get a new one each time.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 服务端控制goose报文控制块的发布问题
  • ¥15 学习指导与未来导向啊
  • ¥15 求多普勒频移瞬时表达式
  • ¥15 如果要做一个老年人平板有哪些需求
  • ¥15 k8s生产配置推荐配置及部署方案
  • ¥15 matlab提取运动物体的坐标
  • ¥15 人大金仓下载,有人知道怎么解决吗
  • ¥15 一个小问题,本人刚入门,哪位可以help
  • ¥30 python安卓开发
  • ¥15 使用R语言GD包一直不出结果