28 May 2012

jquery - dynamic load of html fragments with script

Sometimes I want to load a fragment of HTML into the current page.

Often this is a blob of HTML that came in as part of a JSON object from AJAX. Also, I only might to extract part of the HTML that's returned - because for example sometimes the incoming fragment may be a whole partial view and I only want part of it.

( Note : this is similar to the jQuery $('#target').load('mypage.aspx #divToExtract') syntax )

Well, if you want to do it WITHOUT running script from the incoming fragment, do this:

                        var frag = $(jsonObj.HtmlFragment);
                        frag = frag.find('#divToExtract');
                        $('#target').html(frag.html());
But if you do want to run any script in the fragment, do this:
                        var frag = $('<div />');
                        frag.html( jsonObj.HtmlFragment );
                        frag = frag.find('#divToExtract');
                        $('#target').html(frag.html());

No comments:

Post a Comment

Comments are very welcome but are moderated to prevent spam.

If I helped you out today, you can buy me a beer below. Cheers!