clipboard copy does not work in jquery ajax success method

后端 未结 6 1573
Happy的楠姐
Happy的楠姐 2021-01-14 03:38

I want to copy a card number into the clipboard so that I can paste it in Notepad. The code which I got from the internet works very well if tried in the developer toolbar o

6条回答
  •  無奈伤痛
    2021-01-14 04:21

    What @Anton said was good but it is all bad practice because You are depending on the server to give You a response at a given time which is bad, You can see in all the big websites that have complicated backend that they just put it in an HTML object so the user could copy it via ctrl+c or via button click, I would've done it a lil bit differently than Antons way

    $('#btn').on('click', function(e){
    
        var url = 'Your-link.com';
        var $temp = $("");
        $.ajax({
          type: "POST",
          url: url,
          success: function(res) {
            $("body").append($temp);
            $temp.val(res);
          },
          error: function() {
             //handle error and do something
          }
        });
        setTimeout(function() {
            var $input = $("input#copy_container");
            if ($input.length && $input.val().length > 0) {
                $input.select();
                document.execCommand("copy");
                $input.remove();
            }
        }, 500)
    });   
    

    this way You dont need to reuse event listeners, yet like I said before its far from perfect. Better put it in a HTML element shown to the user.

提交回复
热议问题