How to load a page content in variable with jQuery

2.6k Views Asked by At

A little problem here.

I'm trying for 2 hours to load/get/steal my own content page in jQuery/JS variable (I'm trying to understand the logic behind the beast).

Now we are, my problem:

$(document).ready(function(){
    var string = $.get( "/main.html", function( data ){
                    return $(data).html();
                }, "html");
    alert($(string).html());
    document.title = 'Test ~ Main';
    return false;
});

I'm hardly trying to get the content of the main.html page to save it in a variable to permit me to fast load content with .

My main.html page is a simple:

<html>
   <h1>Welcome on main page</h1>
   <p>Welcome again on main page</p>
</html>

Once i had a null alert and after some modifications i got an Object object. I was google.load() 1.4.1 cause i'm reading a tut on jQuery and i switched to 1 to see if there wasn't an improvement. Before that i catched xmlhttprequest return value ...

So more tests, changements, icecreams and the jQuery.get() doc/manual isn't helping me a lot.

Thank's to all incoming answers.

A french computer science student.

EDIT : There, it is my all script tags -> http://pastebin.com/pu43wrq2 Maybe the problem is inside. And that's to dodge the load("/main.html") that i want to store main.html, work.html and contact.html (once and only once) in an array (for exemple) to fast page switch.

1

There are 1 best solutions below

3
On BEST ANSWER

data is the output from another file you connected with js .. in your case data already html .. so try to use

$(document).ready(function(){
    var string;
    $.get( "/main.html", function( data ){ // check your main.html path
                    alert(data); // check data 
                    string = data; // make string from the data
                }, "html");
    alert(string); // alert string
    document.title = 'Test ~ Main';
    return false; // no need to return false
});

with this code you should get 2 alerts .. its same content but 1st one from data and 2nd from string

if you got empty alert then check your main.html path