剪贴板复制在jquery ajax成功方法中不起作用 [英] clipboard copy does not work in jquery ajax success method

查看:102
本文介绍了剪贴板复制在jquery ajax成功方法中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将卡号复制到剪贴板中,以便将其粘贴到记事本中.如果在浏览器的开发人员工具栏中尝试,我从互联网获得的代码将非常有效.但是,如果我将该代码添加到我的Javascript文件中并运行该项目,则它将无法正常工作.以下是代码:

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 of the browser. However if I add that code into my Javascript file and run the project then it does not work. Following is the code:

$.ajax({
  type: "POST",
  url: '@Url.Action("CopyToClipboard", "MyAccountSurface")',
  data: {
    controlId: controlId
  },
  dataType: 'json',
  success: function(data) {
    var $temp = $("<input>");
    $("body").append($temp);
    $temp.val(data.CardNumber).select();
    document.execCommand("copy");
    $temp.remove();
    alert('copied successfully');
  }
});

推荐答案

如果您希望在使用Ajax单击时复制到剪贴板中

您要单击的元素有很少的事件:鼠标单击.然后按此顺序触发它们.这意味着您可以在第一个请求中发送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.

让我分享工作示例:

  $link.on("mousedown", function() {
    var url = $(this).data("url");
    var $temp = $("<input id='copy_container' style='position:fixed;left:-200px;'>");

    $.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)
  })

您需要100毫秒的超时时间来等待ajax响应.可以根据需要进行改进.

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.

这篇关于剪贴板复制在jquery ajax成功方法中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆