开发者

How to access javascript variables in dynamically-loaded html page?

I've got a html page which loads another html page into one of its divs via Ajax. Something like:

Base html page:

<html>
  <head>
    <script type='text/javascript'>
      var greeting = "Hello";
    </script>
  </head>
  <body>  
    <div id="details-main-content">
    </div>
  </body>
</html>

Page that gets loaded into the one above (uses django templating so whatever is placed in the 'head' block ends up in the 'head' tag of the base page):

{% block head %}
  <script type="text/javascript" language="javascript">
    alert("Greeting: " + greeting);
  </script>
{% endblock %}
<div>
  Hello, world!
</div>

The child content gets loaded when a button is clicked, via a Javascript function (using JQuery) such as this:

function loadContent(url) {
    // Load external content via AJAX. 
    $( '.details-main-开发者_运维百科content' ).load( "/foo.html", function(){        
    });
}

The page loads correctly, the child content displays exactly desired, inside the templatepage.

Is it possible to access the JS variables in the base page from the inner page (since the inner page is nestled inside of the outer page)?

Any help is greatly appreciated.

Thanks

EDIT:

I think the issue I was having was due to having the following line in the of the base html page:

var gender = null;
var age = null;

Which, each time a new page would be loaded through the load() function, would re-init the variables back to null. Oops


Yes. It's just a single page, before and after the load (which uses XMLHttpRequest). As a simple example, if you had:

var message = "Annoying message";

you could have

<a href="#" onclick="alert(message);">Message</a>

in the inner page.

EDIT: If you're having issues, it might be due to the issue noted on the jQuery load documentation:

During this process, browsers often filter elements from the document such as <html>, <title>, or <head> elements. As a result, the elements retrieved by .load() may not be exactly the same as if the document were retrieved directly by the browser.


There is no "inner" and "outer" page in your example. You just work with single page, some content of which is loaded dynamically, but it is not treated any differently by the browser.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜