57

I know I can load in html in to a div with:

$("#my_div").load("http://www.mypage.com");

but I want to do is load html into a variable like:

my_var = load("http://www.mypage.com");

Any help is great.

I would like to loop though some items like:

HLS.functions.LoadSideModules = function() {
    HLS.sideModuleContent = new Object();
    for(var i = 0; i < HLS.currentModuleConfig.POLICIES.POLICY.length; i++) {
        for(var y = 0; y < HLS.currentModuleConfig.POLICIES.POLICY[i].PAGES.PAGE.length; y++) {
            for(var POS in HLS.currentModuleConfig.POLICIES.POLICY[i].PAGES.PAGE[y]) {
                var item = HLS.currentModuleConfig.POLICIES.POLICY[i].PAGES.PAGE[y][POS];
                if(!HLS.sideModuleContent[item]) {
                    HLS.sideModuleContent[item] = j.get(HLS.config.K2GETMODULE + HLS.currentModuleConfig.POLICIES.POLICY[i].PAGES.PAGE[y][POS]);
                }
            }
        }
    }
};

5 Answers 5

88
$.get("http://www.mypage.com", function( my_var ) {
    // my_var contains whatever that request returned
});

Underneath, jQuery will launch an ajax request which fires to the given URL. It also tries to intelligently guess which data is going to be received (if it's valid html you don't need to specify). If you need to get another data type just pass that in as last argument, for instance

$.get("http://www.mypage.com", function( my_var ) {
    // my_var contains whatever that request returned
}, 'html');  // or 'text', 'xml', 'more'

Reference: http://api.jquery.com/jQuery.get/

Sign up to request clarification or add additional context in comments.

2 Comments

It works for me, but shows error in console after load: "Uncaught SyntaxError: Unexpected token <" . Any idea why?
@Darius.V it's been some time since you asked this question but for others who may have come across this problem - you probably put <script> tag in console. Remove it and it should work.
43

You could also create an element in memory and use load() on it:

var $div = $('<div>');

$div.load('index.php #somediv', function(){
    // now $(this) contains #somediv
});

The advantage is that you can specify which part of index.php you want to load by using a selector ( #somediv )

Comments

2

While creating a new element is one option, you could also clone any element. This copies all the attributes and the values of the old Node, as it says, 'exact clone'.

In case you want only a particular section of the html to be copied, this also provides the flexibility to fill all the contents within the particular element hierarchy (i.e., with all the children included) from the fetched page.

For instance, if the hierarchy is -

<div id='mydiv'>
    <div>
        <span>
        ...</span>
    </div>
</div>

//...

var oldElement = document.getElementById('mydiv');
var newElement = oldElement.cloneNode(true);

/* #selector selects only that particular section & the '> *' enables to copy all of the child nodes under the parent #selector
Replace URL with the required value
function specification is optional... */

jQuery(newElement).load(URL+'#selector > *'[,function(response, status, xhr){}]);

//...

Now you can programatically process the variable newElement as you want (using native javascript as well, since it is a native element).

Comments

2
    function includeHTML_callBack(result){
        var my_var = result;
    }

    function includeHTML(link, callBack) {
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                callBack(this.responseText);
            }
          }      
          xhttp.open("GET", link, true);
          xhttp.send();
          return;
    }

    includeHTML("http://www.mypage.com", includeHTML_callBack);

Comments

0

nowadays modern browser has a fetch api,
which can do sync or async style call.

sync style call:

var resp = await fetch(the_url)
var text = await resp.text()

NOTE: await is only valid in async functions and the top level bodies of modules


https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
https://developer.mozilla.org/en-US/docs/Web/API/Response/text
https://stackoverflow.com/a/41946517/4896468

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.