【问题标题】:How to prevent the changing of integer onreadystatechange如何防止整数onreadystatechange的变化
【发布时间】:2016-12-17 17:37:05
【问题描述】:

我的 Ajax 有问题。目前,我有 5 对元素:下拉列表(span 标签)和下拉列表的内容(ul 标签)。在span 标签上是一个事件监听器,对于onclick,如果单击,drop-downs 会出现,当单击其他地方时,下拉菜单会消失。使用硬编码的li,下拉菜单可以正常工作。但是,我正在尝试使用 ajax 使用动态生成的<li>s 填充<ul>s。然而,Ajax 行为不端。

span 上,我还有另一个onchange 的事件监听器,它调用js 函数calloptions();,这是我的Ajax。我想要实现的是,如果您选择一个选项,其他下拉列表中的选项会根据您选择的内容而变化。我的功能是onchange,从下拉列表0循环到下拉列表5,根据所有选择的值更改<li>

但是,当我调试时,我的值 [k] 会在第一个循环中 readyState 变为 [4] 时更改为 5?我不确定循环 1 上 [k] 值的增加是由于 onreadystatechange 还是我完全遗漏的其他原因。因此,这会导致函数无法覆盖<ul>值,因为它正在寻找span[5],而其中只有5个,然后打印Cannot read property 'parentElement' of undefined (...)

HTML

    <div id="filters">
        <div class="i_drop col column-2">
            <span class="i_drop_select"></span>
            <img class="i_drop_select_function drop" src="./assets/drop_input.png">
            <ul class="i_drop_content"></ul>
        </div>
        <div class="i_drop col column-2">
            <span class="i_drop_select"></span>
            <img class="i_drop_select_function drop" src="./assets/drop_input.png">
            <ul class="i_drop_content"></ul>
        </div>
        <div class="i_drop col column-2">
            <span class="i_drop_select"></span>
            <img class="i_drop_select_function drop" src="./assets/drop_input.png">
            <ul class="i_drop_content"></ul>
        </div>
        <div class="i_drop col column-2">
            <span class="i_drop_select"></span>
            <img class="i_drop_select_function drop" src="./assets/drop_input.png">
            <ul class="i_drop_content"></ul>
        </div>
        <div class="i_drop col column-2">
            <span class="i_drop_select"></span>
            <img class="i_drop_select_function drop" src="./assets/drop_input.png">
            <ul class="i_drop_content"></ul>
        </div>
    </div>

AJAX

function calloptions() { 
var toselect = ["class", "topic", "subtopic", "year", "marks"];
for (var k = 0; k < toselect.length; k++) {

    var filters = document.getElementById("filters"); 
    var span = filters.getElementsByTagName("span");
    var execute = "select";
    var myclass= span[0].innerHTML;
    var topic =span[1].innerHTML;
    var subtopic = span[2].innerHTML;
    var year = span[3].innerHTML;
    var marks =span[4].innerHTML;

    makeRequest('test.php', toselect[k],  myclass, topic, subtopic, year, marks, execute); 

    function makeRequest(url, select, myclass, topic, subtopic, year, marks, execute) {

    httpRequest = new XMLHttpRequest();

    if (!httpRequest) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
    }

    httpRequest.open('POST', url);
    httpRequest.onreadystatechange = alertContents;
    httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 
    httpRequest.send("function="+ execute+ "&toselect="+ select+ "&class=" + encodeURIComponent(myclass) + "&topic=" + encodeURIComponent(topic) + "&subtopic=" + encodeURIComponent(subtopic) + "&year=" + encodeURIComponent(year) + "&marks=" + encodeURIComponent(marks));
    }

    function alertContents() {
        if (this.readyState == 4 && this.status == 200) {
            var response = this.responseText;
            var container = span[k].parentElement || span[k].parentNode ;
            var ul =container.getElementsByTagName("ul")[0];
            ul.innerHTML = response;
        }
    }
}
}

PHP

if(!empty($_POST['function']) && !empty($_POST['toselect']))
{
    $toselect = $_POST['toselect'];
    $_POST['function']($toselect);

}

function select($toselect) {
    global $link;

    $variables = "";

    $select_options = array("class", "topic", "subtopic", "year", "marks");     

    $unset_options= array(); $set_options= array(); $set_values= array();

    for ($i=0; $i < count($select_options) ; $i++) { 
        if(isset($_POST[$select_options[$i]]) && $_POST[$select_options[$i]] != ''){
            array_push($set_options, $select_options[$i]);
        } else {
            array_push($unset_options, $select_options[$i]);
        }
    }

    for ($i=0; $i < count($set_options) ; $i++) { 
        array_push($set_values, $_POST{$set_options[$i]});
    }

    for ($i=0; $i < count($unset_options); $i++) { 
        $key = array_search ( $unset_options ,  $select_options);

        unset($select_options[$key]);
    }

    $select_options = array_values($select_options);

    for ($i=0; $i < count($set_options) ; $i++) { 
        if ($i<1) {
            $variables .= " $set_options[$i]='$set_values[$i]'";
        } else {
            $variables .= " AND $set_options[$i]='$set_values[$i]'";
        }
    }

    if ($variables != "") {
        $variables = "WHERE" . $variables;
    }

    $sql="SELECT DISTINCT $toselect FROM `questions` $variables";

    $result=mysqli_query($link, $sql);

    $test_array = array();

    $i = 0;

    while ($row =mysqli_fetch_array($result)) {
        $test_array[$i] = "<li>$row[0]</li>";
        $i++;
    }

    $test_array = implode("", $test_array);

    echo $test_array;       
}

我在httpRequest.send() 打印了提交给PHP 文件的参数,并将它们作为$_GET 在文件中运行,它可以工作,所以我知道这不是PHP 的问题,而是我的失败阿贾克斯。

我希望能提供任何更简单的算法/方法来实现预期目标,但更希望能帮助我消除当前的错误。我是 Ajax 和 javascript 的新手,因此,我也非常感谢您稍微简化一下。谢谢!

【问题讨论】:

  • .open()方法中将异步参数设为false,像这样:httpRequest.open('POST', url, false);。如果你把异步参数设置为false,不要写任何onreadystatechange函数,只要把代码放在.send()之后。
  • 我还没有完全测试你的想法,但从我实施的情况来看,我收到一个错误,说Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/. 虽然它可能有效,但它已被弃用。为了将来的知识,我想找出一种有效的方法来实现这一点......无论如何,谢谢。

标签: javascript php html ajax


【解决方案1】:

目前,我还没有找到导致我“过度增加”[k] 值的原因,但通过实验,将 for 循环和 Ajax 分开是有效的。像这样:

function externalFunction() {

    var toselect = ["class", "topic", "subtopic", "year", "marks"];
    for (var i = 0; i < toselect.length; i++) {
        calloptions(i, toselect[i]);
    }
}


function calloptions(x, toselect) { 

    var form = document.getElementById("filters"); 
    var span = form.getElementsByTagName("span");
    var execute = "select";
    var myclass= span[0].innerHTML;
    var topic =span[1].innerHTML;
    var subtopic = span[2].innerHTML;
    var year = span[3].innerHTML;
    var marks =span[4].innerHTML;

    makeRequest('test.php', toselect,  myclass, topic, subtopic, year, marks, execute); 

    function makeRequest(url, toselect, myclass, topic, subtopic, year, marks, execute) {

        httpRequest = new XMLHttpRequest();

        if (!httpRequest) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }

        httpRequest.onreadystatechange = alertContents;
        httpRequest.open('POST', url);
        httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 
        httpRequest.send("function="+ execute+ "&toselect="+ toselect+ "&class=" + encodeURIComponent(myclass) + "&topic=" + encodeURIComponent(topic) + "&subtopic=" + encodeURIComponent(subtopic) + "&year=" + encodeURIComponent(year) + "&marks=" + encodeURIComponent(marks));
}

    function alertContents() {
        if (this.readyState == 4 && this.status == 200) {
            var response = this.responseText;
            var container = span[x].parentElement || span[x].parentNode ;
            var ul =container.getElementsByTagName("ul")[0];
            ul.innerHTML = response;
    }
}

搜索还没有结束,还在努力解决......

【讨论】:

  • 请看我的回答
【解决方案2】:

k 值的增加并不是由于一些神秘的 ajax/scope 问题,实际上是由于for 循环。 k 会增加,即使 你的条件不合格 是的!你没听错,我承认这真的很奇怪。当你循环结束时k 已经等于 5 请注意 atm。还没有响应。由于您的所有回调都在同一个函数中,它们都引用相同的k,其值为 5,这就是您看到错误的原因

for (var k = 0; k < toselect.length; k++) {
//....
//
}

console.log(k); //5

你能做什么? 好吧,您可以在回调函数中简单地使用k-1,或者只使用其他一些变量自己增加它,但这只会消除这个错误并且仍然是错误的,因为当响应到来时,他们都会看到 k 具有相同的值并更新相同的@ 987654327@.解决异步。我们通常使用闭包的问题尝试搜索,如果您有任何疑问可以问我。

【讨论】:

    猜你喜欢
    • 2020-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-24
    • 1970-01-01
    相关资源
    最近更新 更多