Lotus@ 2015-12-23 17:39 采纳率: 100%
浏览 11

下载提交

The download

var link = document.createElement("a");
link.download = name;
link.href = uri;
link.click();

is working without being in jQuerys' submit.

But here

$('form').submit(function(e) {
    e.preventDefault(); 

    var uri = $(this).find("input").attr("data-uri");
    var name = $(this).find("input").attr("data-name");
    alert(uri); // Does work!

    // This download does not work ...
    var link = document.createElement("a");
    link.download = name;
    link.href = uri;
    link.click();
    // Download end

    $.ajax({
      url: 'entry.php',
      type: 'POST',
      data: $(this).serialize()
    });
});

it does not work. The uri and the name are correct.

Is it possible to create elements after submitting?

What can be done to make the download work?

  • 写回答

1条回答 默认 最新

  • weixin_33720452 2015-12-23 17:55
    关注

    .click() is an event listener. I think you're looking for .trigger('click')

    Also, href is the link reference of an anchor tag - e.g. the file you want to link to. Download is a newer attribute of the anchor tag made to download. Both values in this case should be the same for you, so I'm not sure why you're using the uri and the name as separate components. I've left both intact below, but you may want to consider this.

    Also, you're creating an <a> element, but you're never actually adding it to the DOM. Try this:

    $('form').submit(function(e) {
        e.preventDefault(); 
    
        var uri = $(this).find("input").attr("data-uri");
        var name = $(this).find("input").attr("data-name");
        alert(uri); // Does work!
    
        // This download does not work ...
        var link = document.createElement("a");
        link.download = name;
        link.href = uri;
        $(document).append(link); // Add your link to the DOM
        link.trigger('click'); // Trigger the click of your link
        // Download end
    
        $.ajax({
          url: 'entry.php',
          type: 'POST',
          data: $(this).serialize()
        });
    });
    

    I would also suggest looking into the .data() jquery function to find your inputs.

    评论

报告相同问题?