How to embed iFrame with external website

隐身守侯 提交于 2021-02-19 08:17:07

问题


I am learning web development and trying to achieve task of adding external webpage to a simple HTML page. So, I have a text box where I need to put the URL and based on that the iframe should render. Webpage renders properly when src attribute is loaded directly using .attr property of jquery.

Working example without the text field:

HTML

<div id="mydiv">
     <iframe id="frame" src="" width="100%" height="300">
     </iframe>
 </div>
 <button id="button">Load</button>

SCRIPT

$(document).ready(function(){
$("#button").click(function () { 
    $("#frame").attr("src", "https://www.wikipedia.org/");
});
});

Below is what I want

HTML

Enter the URL
    <input id="url" type="text"/>
      <div id="mydiv">
             <iframe id="frame" src="" width="100%" height="300">
             </iframe>
         </div>
         <button id="button">Load</button>

Script

<script>
$(document).ready(function(){
    $("#button").click(function () { 
    var x = $("#url").val();
        $("#frame").attr('src', 'x');
    });
});
</script>

I referred this SO LINK but could not find the answer. My JSfiddle novice attempt tells an error message as {"error": "Please use POST request"}. Do I need to use load jquery method. I just want to read the content of textbox and open the page in iframe with a buttons click. Link to my JSFiddle


回答1:


Can you try this simple example - I've defaulted the input to https://en.wikipedia.org but you can try other URLs in there.

$(document).ready(function(){
  $("#button").click(function () { 
      var url = $('#url').val();
      $("#frame").attr("src", url);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="mydiv">
    <input id="url" type="text" value="https://en.wikipedia.org"/>
     <iframe id="frame" src="" width="100%" height="300">
     </iframe>
 </div>
 <button id="button">Load</button>


来源:https://stackoverflow.com/questions/40903065/how-to-embed-iframe-with-external-website

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!