tags:

views:

14

answers:

1

I'm trying to create a simple ajax load test script that dynamically creates divs, runs an external php script and return the result to the created div.

I'm trying to figure out how to create a for-loop that creates, say 10 divs and runs the php script for all divs. Preferably so that I can specify which script to run.

This is the code so far. It works but at the moment only one div is created.

<html>
<head>
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<style>
    .running { background-color: yellow; }
    .completed { background-color: green; }
}
</style>
<script>
    function RunScripts() {

        // Create a new div
        $('#container').append('<div id="div1" class="running"></div>');

        // Run a php script and return the content
        $.get("getcontent.php",
            function(data){
                $('#div1').html(data);
                $('#div1').removeClass('running').addClass('completed');
            }
        );
    }
</script>
</head>
<body>
    <a onclick="RunScripts();">Run test</a>
    <div id="container"></div>  
</body>
</html>

How can I improve the script so that it can create and run multiple scripts at the same time?

+1  A: 

You can use setTimeout to run multiple instances of a function, ie.

setTimeout('RunScripts()', 0);
setTimeout('RunScripts()', 10); //Run again after 10ms.

Maybe this can help you?

You would also have to create new divs in order not to overwrite response data, something like:

    // Create a new div
    var $div = $('<div>')
      .addClass('running')
      .appendTo('#container');

    // Run a php script and return the content
    $.get("getcontent.php",
        function(data){
            $div.html(data);
            $div.removeClass('running').addClass('completed');
        }
    );
sewa
Thank you! So simple, yet so powerful
Tom