javascriptjquerypythonajaxweb2py

Get variable and page fragment using Jquery .load() function


I am currently using Jquery's .load() function to insert a page fragment asynchronously. In the URL that I am loading the page fragment from, I also set a Javascript global variable value (in the script tag).

var loaded_variable = 'value1'

Is there a way I can use the .load() function to insert the page fragment AND retrieve the value of loaded_variable, something like the following code:

    function loadProducts(url) {
                 $('#mainplace').load(url + ' #submain', function() { 
                       current_variable = loaded_variable;
                 });
    }

I am aware that script blocks are used when a selector expression is appended to the URL, so if the .load() function won't work, I'm open to other Jquery functions that can accomplish this.

Extra Info: The URL that I am loading from is written in HTML and Python (Web2py); the same Python variables are used to render the page fragment and set the loaded_variable value.


Solution

  • If you want to both fetch a fragment from a page and execute a script on it, you'll need a different approach. This is a bit hacky, but works.

    $.ajax({url: 'fetch_page.html', dataType: 'text'}).done(function(html) {
        var dom = $('<html />').prop('innerHTML', html);
        $('body').append(dom.find('body p'));
        $('head').append(dom.find('script'));
    });
    

    That fetches a p tag from our fetched pages and inserts it into the body of the parent page. It also executes any scripts in the fetched page.

    If you're wondering about the prop('innerHTML... bit, that's because if I'd used jQuery's .html() method, it sanitises the input string and so we don't get the result we want.

    My first thought was a document fragment, but you can't insert an HTML string into a doc frag - you have to append via DOM methods. Even then in this case it wouldn't really offer any saving over simply using an element to parse the dom (dom) as I have.

    Bit hacky, as I say, but works.