Reputation: 5621
I am writing a single page web application for Microsoft SharePoint.
I'd like to pull in content with $.get()
, but I've run into a bit of a catch 22.
If I pull in the content like this:
function getLocalPage(url, callback) {
$.get(url, function(data) {
var $page = $(data).filter('.tileContent').html();
callback($page);
});
}
I get the node I'm looking for, but my script tags have been stripped out.
If I pull in content like this: (reference to: jquery html() strips out script tags )
function getLocalPage(url, callback) {
$.get(url, function(data) {
var dom = $(data);
dom.filter('script').each(function(){
$.globalEval(this.text || this.textContent || this.innerHTML || '');
});
var $page = dom.filter('.tileContent');
callback($page);
});
}
The javascript embedded in SharePoint blows my page up, and seems to cause a full postback.
Is there any way to get only the node I would like, with the script tags intact?
Can't seem to have it both ways.
Upvotes: 0
Views: 232
Reputation: 18078
Rather than the shorthand jQuery method .get()
, try .ajax()
with dataType: 'html'
The .ajax()
documentation says of dataType: 'html'
:
"html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
It also says :
"If 'html' is specified, any embedded JavaScript inside the retrieved data is executed before the HTML is returned as a string."
The emphasis here is on the word "before" meaning that the embedded JavaScript, when executed, cannot act directly on the HTML with which it is delivered (or a resulting DOM-fragment), though it can act directly on the existing DOM, prior to fragment insertion.
However, any functions included in the embedded JavaScript do indeed become available to act on the HTML/DOM-fragment and the DOM at large, if called later. The first opportunity to call such functions is in the .ajax()
success handler (or chained .done()
handler).
Unless extraordinary (and potentially messy) measures are taken, the success handler (or any functions called by it) will need prior "knowledge" of the names of any functions that are delivered in this way, otherwise (realistically) they will be uncallable.
I'm not sure about code delivered inside a $(function() {...});
structure, which may execute when the current event thread has completed(?). If so, then it could potentially be made to act on the delivered HTML/DOM-fragment. By all means try.
With all that in mind, try the following approach, with appropriately phrased JavaScript in the response.
function getLocalPage(url, callback) {
$.ajax({
url: url,
dataType: 'html',
success: function(data) {
callback($(data).find('.tileContent'));
}
});
}
or better :
function getLocalPage(url, callback) {
$.ajax({
url: url,
dataType: 'html'
}).done(function(data) {
callback($(data).find('.tileContent'));
});
}
Notes:
.filter()
to .find()
, which seems more appropriate but you may need to change it back..ajax()
options.Upvotes: 1