Using jQuery 1.7.3
I’ve recently replaced a $.load(); call with a $.get(); in one of my scripts to take advantage of request aborting and other cool features – so I’m requesting a normal (php in this case) html page rather than a file that returns JSON or XML.
But I’ve noticed that a script error on the page you are loading – for example onError='myFunction(this);' inline scripts that call a function not defined on page1 but present on page2, can throw an error (in this case, undefined function myFunction) on page1. Also I see the images are requested too.
My use case is that I need one div worth of data from the new page, not the whole thing and certainly not the images – is there a way to get jQuery to request only the markup and not ‘follow’ the image links, nor attempt to run any inline scripts?
Example:
Page1:
$.get('page2', {someData:123}, function(data){
var myDiv = $('#myDiv', data); //get the div I want from the response
//but at this point the browser has run the inline
//scripts and requested the images :(
//do something with the (very expensive) data
$('body').append(myDiv);
});
Page2:
<div id='myDiv'>
<!-- some dynamic data that changes over time -->
</div>
There are some concerns about whether I should just write (yet another) file I can query with JSON to get the data I need, then parse it in the script and generate the markup, etc etc, but sufficed to say in this use case that would be far more trouble than it’s worth, especially considering I’d be replicating code too.
With regards the inline scripts, I can (and have, as a workaround) just define the function on page1 to avoid the error.
Any help appreciated
The best way to do this that I eventually found is pretty simple – when you make an AJAX request to a page, send in an extra parameter that stops your page from outputting data you don’t need.
This approach is a pain to implement, but does the job and is nice and efficient when you have a very big search page that does all sorts of extra stuff, but all you want is the next page of results.