0

I am loading an html page through ajax which contains a JS object. How do you get a reference to the object inside the freshly loaded (child) page to the parent page?

Parent:

//parent.html

<script>

    function ParentObject() {
        this.children = new Array();
    }

    var aParentObject = new ParentObject();

    $.get('/url/to/child.html', function(data) {
        $("#child-div").html(data);
    });

</script>

Child:

//child.html

<div>Some html element</div>

...

<script>
    function ChildObject() {
        this.someProperty = "I'm a Child";
    }

    var aChildObject = new ChildObject();
</script>
1
  • Try console.log(aChildObject) after your html function. You should be able to view the child object instance I think. Commented May 25, 2012 at 9:01

2 Answers 2

2

You should use var when you declare new variable

var aChildObject = new ChildObject();

When you append a html containing a jscript the script will execute and you will get reference after that point. So you must ensure that you access the child variable after you insert it.

$.get('/url/to/child.html', function(data) {
    $("#child-div").html(data);
    //Access your child here
    alert(aParentObject.someProperty);
});
Sign up to request clarification or add additional context in comments.

2 Comments

Did you mean alert(aChildObject.someProperty)?
aah Yes, sorry, alert(aChildObject.someProperty)
0

You might want to use .load() in place of .get(). With .load() you can specify a selector for the "child" page to pull back a specific part that you want to retrieve.

Assuming that child.html's div has id="child-div":

//parent.html

<script>

    function ParentObject() {
        this.children = new Array();
    }

    aParentObject = new ParentObject();

    $("#child-div").load('/url/to/child.html #child-div');

</script>

See the "Loading Page Fragments" section here: http://api.jquery.com/load/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.