繁体   English   中英

如何通过 AJAX 在 div 中加载 iFrame

[英]How to load iFrame in div by AJAX

我想通过 AJAX 在我的div加载一个 iFrame。 我该怎么做?

<button id="iframeload">Load Iframe</button>
<div id="iframe_content"></div>

<script src="http://code.jquery.com/jquery-1.12.4.min.js"></script>

<script type="text/javascript">
    $('.iframeload').click(function(event) {
      event.preventDefault();
      event.stopImmediatePropagation();
      $.ajax({
          type: "POST", 
          url : "https://pecom.ru/ru/calc/?iframe=Y",
          success : function (data) {  
              // alert('ok');
              $("#iframe_content").html(data); 
          }
      });
  });
</script>

这是 iFrame

<iframe id="pecom-kabinet-iframe" allowtransparency="true" frameborder="0" width="800" height="1800" scrolling="auto" style="border: 0;" src="https://pecom.ru/ru/calc/?iframe=Y">Not supported browser< / iframe >

并且按钮#iframeload不起作用...

第一个错误

您正在使用元素类,而不是代码中的 id:

<button id="iframeload">
$('.iframeload').click(function(event) {

第二个错误

看起来您希望 ajax 调用与您的页面所在的域不同。 因此浏览器会阻止它,因为出于安全原因,它通常允许来自同一来源的请求。

可能的解决方案

但是,如果您只想在单击按钮时显示 iframe 内容,则不需要 ajax。

只需使用attr('scr',url)

 $( document ).ready(function() { $('#iframeload').on('click',function(event){ event.preventDefault(); event.stopImmediatePropagation(); var url = 'https://pecom.ru/ru/calc/?iframe=Y'; $('#abc_frame').attr('src', url); }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <button id="iframeload">Load Iframe</button> <div id="iframe_content"> <iframe name="abc_frame" id="abc_frame" src="about:blank" frameborder="0" scrolling="no"></iframe> </div>

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
   $('#iframe').attr('src', 'https://www.qries.com');
});
</script>
</head>
<body>

<iframe id="iframe" name="myIframe" frameborder="5" width="500" height="300"></iframe>

</body>
</html>

我认为下面的代码可以帮助你。 你需要改变

$('.iframeload') 到 $('#iframeload') 因为您使用的是元素 ID 而不是类

完整的代码如下

 $('#iframeload').click(function(event) { event.preventDefault(); event.stopImmediatePropagation(); $.ajax({ type: "POST", url : "https://pecom.ru/ru/calc/?iframe=Y", success : function (data) { // alert('ok'); $("#iframe_content").html(data); } }); });
 <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script> <button id="iframeload">Load Iframe</button> <div id="iframe_content"></div>

由于API,上面的代码不起作用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM