clipboard copy does not work in jquery ajax success method

后端 未结 6 1595
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条回答
  •  猫巷女王i
    2021-01-14 04:21

    If you want to copy into clipboard on click with Ajax

    Element, which you are going to click has few events: mousedown and click. And they are triggered in this order. It means that you can send ajax request in first one and work with result in last one and in this case you will not have security problems.

    Let me share working example:

      $link.on("mousedown", function() {
        var url = $(this).data("url");
        var $temp = $("");
    
        $.ajax({
          url: url,
          dataType: "json",
          success: function (data) {
            $("body").append($temp);
            $temp.val(data.text);
          }
        })
      })
    
      $link.on("click", function() {
        setTimeout(function() {
          var $input = $("input#copy_container");
          if ($input.length && $input.val().length > 0) {
            $input.select();
            document.execCommand("copy");
            $input.remove();
          }
        }, 100)
      })
    

    You need this timeout with 100ms to wait for ajax response. It can be improved like you want.

    Fixed and negative position - I think you know why we need it.

提交回复
热议问题