gpt4 book ai didi

javascript - 剪贴板复制在 jquery ajax 成功方法中不起作用

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:41:26 26 4
gpt4 key购买 nike

我想将卡号复制到剪贴板,以便我可以将其粘贴到记事本中。如果在浏览器的开发人员工具栏中尝试,我从互联网上获得的代码效果很好。但是,如果我将该代码添加到我的 Javascript 文件中并运行该项目,那么它将不起作用。以下是代码:

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

最佳答案

更新:

必须执行用户交互才能执行 document.execCommand。因此,在您的情况下,无法从 AJAX 响应中复制文本。 这是浏览器同意的安全措施。

引用W3C API

Copy and cut commands triggered through a scripting API will only affect the contents of the real clipboard if the event is dispatched from an event that is trusted and triggered by the user, or if the implementation is configured to allow this.


用户交互的解决方法

添加的步骤:

  • 使用相对位置将文本框放置在远离网页的位置。
  • 添加一个处于禁用状态的按钮。一旦数据可用,请重新启用该按钮。
  • 单击按钮后,您将能够执行 document.execCommand,因为您是直接与浏览器交互(因此没有 API 中提到的安全问题)

$(document).ready(function() {
$.ajax({
url: 'https://jsonplaceholder.typicode.com' + '/posts/1',
method: 'GET'
}).then(function(data) {
console.log(data);
$('#toBeCopied').val(data.title);
$("#copyIt").attr('disabled', null);
});


});
function copyToClipboard(){
var $temp = $("<input />");
$("body").append($temp);
$temp.val($("#toBeCopied").val()).select();
var result = false;
try {
result = document.execCommand("copy");
} catch (err) {
console.log("Copy error: " + err);
}
$temp.remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="text" value="dummy" id="toBeCopied" style="display:none; position: relative; left: -1000px;">
<b>Below button will be enabled once the data is available from AJAX</b>
<button id="copyIt" onclick="copyToClipboard()" disabled>Copy To Clipboard</button>

关于javascript - 剪贴板复制在 jquery ajax 成功方法中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41361081/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com