如何通过AJAX加载div中的iFrame

新手上路,请多包涵

我想通过 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 不起作用……

原文由 boniq 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 376
1 个回答

第一个错误

您正在使用元素类,而不是代码中的 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>

原文由 toffler 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题