简体   繁体   English

for循环和标准Javascript AJAX的问题

[英]Issue with for-loop and standard Javascript AJAX

I have some issues with a for-loop and AJAX. 我有一些关于for循环和AJAX的问题。 I need to fetch some information from a database, so I pass the incrementing variable to PHP to grab the information and then send it back. 我需要从数据库中获取一些信息,因此我将递增变量传递给PHP来获取信息,然后将其发送回去。 The trouble is that it skips immediately to the maximum value, making it impossible to store any of the information. 麻烦在于它会立即跳到最大值,从而无法存储任何信息。

I would prefer not to use jQuery. 我宁愿不使用jQuery。 It may be more powerful, but I find Javascript easier to understand. 它可能更强大,但是我发现Javascript更容易理解。

Here is the JS code: 这是JS代码:

for (var i = 0; i <= 3; i++) {
    var js_var = i;  
    document.getElementById("link").onclick = function () {            
        // ajax start
        var xhr;
        if (window.XMLHttpRequest) xhr = new XMLHttpRequest(); // all browsers
        else xhr = new ActiveXObject("Microsoft.XMLHTTP");     // for IE

        var url = 'process.php?js_var=' + js_var;
        xhr.open('GET', url, false);
        xhr.onreadystatechange = function () {
            if (xhr.readyState===4 && xhr.status===200) {
                var div = document.getElementById('test1');
                div.innerHTML = xhr.responseText;
                if (js_var == 2) {
                    var rawr = document.getElementById('test2');
                    rawr.innerHTML = xhr.responseText;
                }
            }
        }
        xhr.send();
        // ajax stop
        return false;
    }
};

Here is the PHP code: 这是PHP代码:

<?php
if (isset($_GET['js_var'])) $count = $_GET['js_var'];
else $count = "<br />js_var is not set!";

$con = mysql_connect("xxx","xxxxx","xxxx");

mysql_select_db('computerparty_d', $con);

$get_hs = mysql_query("SELECT * FROM hearthstone");

$spiller_navn = utf8_encode(mysql_result($get_hs,$count,1));


echo "$spiller_navn";
?>

Be aware that you're making an synchronous AJAX call, which is undesirable (it hangs the browser during the request, which might not end). 请注意,您正在进行同步AJAX调用,这是不希望的(它在请求期间挂起浏览器,但可能不会结束)。 You may have problems in some browsers with this because you're calling onreadystatechange, that shouldn't be used with synchronous requests. 您可能会在某些浏览器中遇到此问题,因为您正在调用onreadystatechange,不应将其用于同步请求。

what you actually are doing is binding an onclick event in your for-loop not sending ajax request, and the other point is, it immediately overrides the previous onclick handler which you have created in the previous iteration. 您实际上所做的是在for循环中绑定一个onclick事件,而不发送ajax请求,另一点是,它会立即覆盖您在上一次迭代中创建的上一个onclick处理程序。

So if you want to add multiple listeners you should first consider using nested functions and closures to keep the i variable safe for each listener, and then use addEventListener instead of setting the onclick function. 因此,如果要添加多个侦听器,则应首先考虑使用嵌套函数和闭包来确保每个侦听器的i变量安全,然后使用addEventListener而不是设置onclick函数。 Considering these points you can do this instead: 考虑到以下几点,您可以改为执行以下操作:

for (var i = 0; i <= 3; i++) {

    var clickFunc = (function (js_var) {
        return function () {
            // ajax start
            var xhr;
            if (window.XMLHttpRequest) xhr = new XMLHttpRequest(); // all browsers
            else xhr = new ActiveXObject("Microsoft.XMLHTTP"); // for IE

            var url = 'process.php?js_var=' + js_var;
            xhr.open('GET', url, false);
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    var div = document.getElementById('test1');
                    div.innerHTML = xhr.responseText;
                    if (js_var == 2) {
                        var rawr = document.getElementById('test2');
                        rawr.innerHTML = xhr.responseText;
                    }
                }
            }
            xhr.send();
            // ajax stop
            return false;
        };
    })(i);

    document.getElementById("link").addEventListener("click", clickFunc);
}

It looks like you are making the AJAX request with a user click. 看起来您是通过用户单击来发出AJAX请求的。

for (var i = 0; i <= 3; i++) {
    var js_var = i;  
    document.getElementById("link").onclick

When this JS is executed it will override the "onclick" listener of "link" twice. 执行此JS时,它将两次覆盖“链接”的“ onclick”侦听器。 First time it is assigned for the first time, second time it is overwritten, and the third time it is overwritten again. 第一次分配,第二次被覆盖,第三次再次被覆盖。 The result is that when the "link" element is clicked only the last listener exists, resulting in making a single AJAX request for the last configuration. 结果是,当单击“链接”元素时,仅存在最后一个侦听器,从而导致对最后一个配置发出单个AJAX请求。

HTTP request are expensive(time), it might be worth to get all of the data in one request and then use client-side JS to sift through that data accordingly. HTTP请求是昂贵的(时间),可能值得在一个请求中获取所有数据,然后使用客户端JS相应地筛选该数据。

jQuery is not more powerful than JS, it is JS with a bunch of wrapper functions. jQuery并不比JS更强大 ,它是带有一堆包装函数的JS。 My personal opinion is that once IE9 is no longer relevant, jQuery will be only used by people who know jQuery and not JS. 我个人的观点是,一旦IE9不再适用,jQuery将仅由了解jQuery而不是JS的人使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM