简体   繁体   中英

how to use for-loop to do form submission in javascript?

I have written a javascript in the console of chrome to download many files from a web. The javascript is as follows:

for (i=0; i<100; i++) {
$("input[name=id]").val(i);
$("form").submit()
}

I expected I can download all the files whose id is from 0 to 99; however, what I am able to download is only the last file (ie file with id =99). Why does this happen?

I think you are missing the responses. When you call first form, the browser start the connection, but just after that, you ask for the second form. Whitch cancel the first.

You need to call that forms with AJAX , to store each request with the correspondent response in some variable.

Your problem is like when you click too many links in a page before let it load the first link. Finally the loaded link is the last clicked.

TRY THIS SOLUTION:

You need to que keep some time between calls to handle response and start the download, so wright a function like this:

function submitFormAndWait(i) {
    //this is your code to submit
    $("input[name=id]:hidden").val(i);
    $("form").submit()
    //wait some time and call next form
    if (i < 100) {
        setTimeout(function(){ submitFormAndWait(i + 1); }, 3000);
    }
}

POSSIBLE PROBLEM:

When you submit a form in the browser, this will load the response as the current page, and the script will start from zero other time.

The best way to do that is using AJAX and FormData.

Assuming you're using jQuery in your site, some pseudocode for this:

var url = '/some/ajax/url';
var i = 0;
for ( ; i < 100; ++i) {
    var formData = new FormData();
    formData.append('some-number-field', i);
    // Send data using Ajax POST
    $.ajax({
        url:  url,
        type: 'POST',
        data: formData,
        success: function(response) {
            // Do something on success
        },
        error: function(xhr, status errorThrown) {
            // Do something on error
        }
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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