Search code examples
javascriptjqueryhtmlsame-origin-policy

Why is JavaScript of the HTML from page2 loaded into page1 not working?


im trying to load html from page2 into page one but its JavaScript won't work, is this same origin policy? if it is how do i bypass this?

Page1:

    <head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>page 1 test</title>
<script src="js/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#thisandthat').click(function() {
    $("#hide").toggle('fast');
    $("#cont").load('testpage2.html #res')
     $("#unhide").toggle('fast');
     console.log ()
});
});
</script>
</head>

<body>
<div id="">
<input id="thisandthat" name="test but" type="button" value="Button" />
<div id="hide" style="background-color:#050; width:100; height:100;">this and other things</div>
</div>
<div id="cont">
</div>
</body>
</html>

Page2

    <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>page 1 test</title>
<script src="js/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#thisand').click(function() {
    $("#unhide").toggle('fast');
    alert ('im in')
});
});
</script>
</head>

<body>
<div id="res">
<input id="thisand" name="test but" type="button" value="Button" />
<div id="unhide" hidden="" style="background-color:#09F; width:100; height:100;">i     apppear</div>
</div>

</body>
</html>

as you can see, javascript needed from page2 is present on page1. Please help.


Solution

  • The problem is that you're using the id selector in your $("#cont").load('testpage2.html #res')

    jQuery will only load that section of page 2, therefore no Javascript is loaded. If you remove the id selector it will load the whole page including the Javascript.

    $("#cont").load('testpage2.html')

    Alternatively, you can place your Javascript within the res div, then that should work.

    On a side note, you're missing various line ending semi colons in your code, which is not good.