0

我正在使用 XMLHttpRequest 调用 PHP 文件,但现在调用没有完成,我不知道为什么。不是 4 ,req.readyState我不知道为什么,因为 PHP 文件没问题,并且完全符合预期(只是回显一个字符串)。

谁能看到我看不到的东西?

function processAjax(id, option) {
    if (option == "lpath") url = "<?php echo $mosConfig_live_site;?>/administrator/components/com_joomlaquiz/getinfo.php?id=" + id;
    else url = "<?php echo $mosConfig_live_site;?>/administrator/components/com_joomlaquiz/getinfo.php?cat=" + id;

    //create AJAX request
    if (window.XMLHttpRequest) { // Non-IE browsers
        req = new XMLHttpRequest();
        req.onreadystatechange = targetDiv();
        try {
            req.open("GET", url, true);
        } catch (e) {
            alert(e);
        }
        req.send(null);
    } else if (window.ActiveXObject) { // IE
        req = new ActiveXObject("Microsoft.XMLHTTP");
        if (req) {
            req.onreadystatechange = targetDiv();
            req.open("GET", url, true);
            req.send();
        }
    }
}
//this function handles the response from the ajax request

function targetDiv() {
    if (req.readyState == 4) { // Complete
        if (req.status == 200) { // OK response
            //all of the code below doesn't happen because its not the option
            if (option == "lpath") {
                var response = req.responseText.split('##');
                var articles = response[0].split(';');
                var quizes = response[1].split(';');

                document.getElementById("article_id").innerHTML = "";
                document.getElementById("quiz_id").innerHTML = "";

                for (var i = 0; i < articles.length; i = i + 2) {
                    if ((i + 1) <= articles.length) {
                        var option = new Option( /* Label */ articles[i + 1], /* Value */ articles[i]);
                        document.getElementById("article_id").options.add(option);
                    }
                }

                for (var i = 0; i < quizes.length; i = i + 2) {
                    if ((i + 1) <= quizes.length) {
                        var option = new Option( /* Label */ quizes[i + 1], /* Value */ quizes[i]);
                        document.getElementById("quiz_id").options.add(option);
                    }
                }

                delete req, articles, quizes;
            } else {
                document.getElementById("catdiv").innerHTML += req.responseText;
                document.getElementById("allchildren").value = req.responseText;
            }
        } else { //failed to get response
            alert("Problem: " + req.statusText);
        }
    }
    document.getElementById("catdiv").innerHTML += "Y U NO COMPLETE?!";
}
4

1 回答 1

3
req.onreadystatechange = targetDiv();

应该

req.onreadystatechange = targetDiv;

运行该行代码后立即调用原始代码targetDiv(),这可能不是您想要做的。固定代码在收到 Ajax 请求后正确调用该函数。

于 2011-11-20T22:01:26.640 回答