开发者

Submit a form multiple times using javascript to download multiple files?

开发者 https://www.devze.com 2023-03-02 00:35 出处:网络
Hey Folks, here\'s the situation: I have a URL that takes two parameters and returns a PDF file. I can also po开发者_如何学编程st a form with two input values to this URL instead.

Hey Folks, here's the situation:

I have a URL that takes two parameters and returns a PDF file. I can also po开发者_如何学编程st a form with two input values to this URL instead.

On another page, I want to trigger a javascript that will send different combinations of parameters to the URL, either by GET or POST, and return each of the files associated with the parameter combinations.

Based on another script I found here, I adapted it and tried this (URL anonymized):

var first = '503113571';
var second = '2046486463';
var url = 'https://www.domain.com/page';

el = document.createElement( 'div' );
el.setAttribute( "id", "targetdiv" );
document.body.appendChild( el );

function download(first, second)
{
    var htm = '<iframe src="' + url + '?a=' + first + '&b=' + second + '"></iframe>';
    document.getElementById('targetdiv').innerHTML = htm;
}

download(first, second);

The iframe is created in the div, and its src attribute is correct--if I copy and paste the src attribute into a fresh window, the file downloads fine. For some reason, when this URL is used in the iframe, the file is never loaded.

I am using GreaseMonkey to run the script on the page, as we don't have access to change the actual web pages themselves. The script runs fine (as all of the code runs, creating the iframe correctly).

Using FireBug's NET panel, after the page loads, I don't see any request to the iframe src.

Any ideas, either on the cause, or what steps I could take to figure it out? Thanks!


A few things:

  1. You can only do a GET request that way, and you're not using the arguments you passed into the download function.
  2. I usually paste code into the Firebug console to test something out.
  3. You should be able to just set window.location to download a file.

    var first = '503113571';
    var second = '2046486463';
    var url = 'https://www.domain.com/page';
    
    function download(a, b) {
        window.location = url + '?a=' + a + '&b=' + b;
    }
    
    download(first, second);
    
  4. If you wanted to use an iframe, this should work without the risk of going to a different page:

    function download(a, b) {
        var newIFrame = document.createElement("iframe");
        newIFrame.src = url + '?a=' + a + '&b=' + b;
        newIFrame.style.display = 'none';
        document.body.appendChild(newIFrame);
    }
    
0

精彩评论

暂无评论...
验证码 换一张
取 消