做,而JavaScript的问题 [英] Do while javascript issue

查看:95
本文介绍了做,而JavaScript的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想while循环,但结果不添加多个岗位中的做派

I'm trying to send multiple post within a do while loop but the result is not added

<script type="text/javascript">
function action() {
    var initval = 1;
    var endval = 5;
    do {
    var action_string = 'txtuser=someone';

    $.ajax({
                    type: "POST",
                    url: "http://localhost/js.php",
                    data: action_string,
                    success: function(result){
                       $('div#append_result').append(initval + ',<br/>');
                     }  
                });
    initval++;
     } while (initval <= endval);
  }
</script>

输出为: 5, 5, 5, 5, 5,

The Output is: 5, 5, 5, 5, 5,

和我需要的输出为: 1, 2, 3, 4, 5,

and I need the output to be: 1, 2, 3, 4, 5,

推荐答案

由于AJAX的异步性,通过你的成功函数运行任何所产生的AJAX请求时,环路已完成和 initval 设置为5,您需要捕获 initval 的状态在每个请求和使用的启动捕捉状态中的成功()方法。关闭超所值是最简单的方式做到这一点:

Due to the async nature of AJAX, by the time your success function runs for any of the resulting AJAX requests, the loop has completed and initval is set to 5. You need to capture the state of initval at the start of each request and use that captured state in the success() method. Closing over the value is the simplest way to do it:

function action() {
    var initval = 1;
    var endval = 5;
    do {
        var action_string = 'txtuser=someone';

        ( function( captured_initval ){
            $.ajax({
                type: "POST",
                url: "http://localhost/js.php",
                data: action_string,
                success: function(result){
                    $('div#append_result').append(captured_initval + ',<br/>');
                }  
            });
        }( initval ) );

        initval++;
    } while (initval <= endval);
}

明白了,虽然,一个或多个请求可以得到红在服务器允许后者则要求首先要完成,这可能会导致 1,2,5,3,4 或类似的东西。

此外,使用一个元素的ID比prefixing散列选择与元素标记名称快得多。另外,您应避免重新查询每一个成功的运行时间DOM为你的结果DIV。抓住这一次,使用它需要的时候:

Also, using an element's ID is much faster than prefixing the hash selector with the elements tag name. Plus you should avoid re-querying the DOM for your result DIV every time the success runs. Grab it once and use it when needed:

function action() {
    var initval = 1;
    var endval = 5;
    do {
        var action_string = 'txtuser=someone',
            $AppendResult = $('#append_result');

        ( function( captured_initval ){
            $.ajax({
                type: "POST",
                url: "http://localhost/js.php",
                data: action_string,
                success: function(result){
                    $AppendResult.append(captured_initval + ',<br/>');
                }  
            });
        }( initval ) );

        initval++;
    } while (initval <= endval);
}

这篇关于做,而JavaScript的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆