views:

378

answers:

3

As I understand it, the JQuery load() function retrieves a document and can perform the quivelent of:

$('#somecontenttograb').html()

upon it. I would like to know how to do that... In essence, I want to use JQuery to asynchronously download a web page and then grab elements from it and insert them into my own document at different places.

I'm thinking the .ajax call is good here, but I'm having trouble understanding the returned object - I believe the argument passed to the success function could have it's elements pulled out, but how?

Thanks,

Matt.

Having tried the code posted in the two answers below, I have tried this and while I can use an alert to show me the url being passed to the ajax() call and the success function gets called, if I alert the $(result).find('#content') only null appears in the alert. If I put the url from the first alert into a browser, I get a valid page back. What could be going wrong?

Matt.

+1  A: 

UPDATE

In response to the comments you've left on other answers, I just want to make sure I understand the situation clearly:

  • You're testing from your localhost, not from the local hard drive (meaning your URL in the browser includes "http://localhost", and not a location on your hard drive.
  • When you make the AJAX response, alert(...)-ing the result give you null, or some equivalent.
  • The URL is valid and can be loaded in your browser.
  • The URL you're requesting is within the same domain as the originating page.

If those things are true, then I'd try the following do some troubleshooting:

  1. Use Firefox and install Firebug (we'll need this to determine if AJAX requests are failing, and why)
  2. Include some logging in your code using Firebug's console
  3. Use jQuery's ajax(...) method, and handle failure by including some logging code to see what happened. You may be able to avoid this step if the page you're on doesn't need a visual response for a failed request and you're using Firebug.

Here's the code I would use for this:

$.ajax({
    url: "http://stackoverflow.com/",
    success: function(html) {
        var responseDoc = $(html);
        // Output the resulting jQuery object to the console
        console.log("Response HTML: ", responseDoc);
    }
    // Handle request failure here
    error: function(){
        console.log("Failure args: ", arguments);
    }
});

If you post the output of your Firebug logs, it should be easier to figure out the problem and find a solution for you. Firebug also logs XMLHttpRequests so you can see exactly what is being sent to and from the server, and Firebug will change the look of the request if it returns some kind of server error (which is how you could avoid #3 of the things I listed above).


You could use the ajax(...) method, but it would be easier to use get(...) with a callback, like this:

$.get("http://stackoverflow.com", function(html) {
    var responseDoc = $(html);
});

responseDoc will be a jQuery object you can use to extract elements from and treat just like you would any other jQuery object. You can extract stuff from the responseDoc and add it into your main document any way you want, using the jQuery manipulation methods.

If you need the extra functionality the $.ajax(...) method provides, you would use the following code.

$.ajax({
    url: "http://stackoverflow.com/",
    success: function(html) {
        var responseDoc = $(html);
    }
    error: function(XMLHttpRequest, textStatus, errorThrown){
        // Handle errors here
    }
});
Dan Herbert
A: 

If the url you are requesting returns html you can use selectors on it:

$.ajax({
    url: '/test.html',
    success: function(result) {
        // select an element that has id=someElement in the returned html
        var someElement = $(result).find('#someElement');
        // TODO: do something with the element
    }
});
Darin Dimitrov
Please see my edit about not receiving a valid return from the find() call.
Matt W
I have tried your code sample with a plain html doc containing just a div with id='someElement' and could not get it to alert anything but null or object [Object]. Could you add some to explain how to use the returned object from the find() call, please?
Matt W
+2  A: 

If the web page in question lives on a different server, you won't be able to use any AJAX to get access to the returned html due to issues with the same origin policy. The only type of data that you will be able to get via AJAX from another server is JSONP. This uses a script tag to load the data and operate with it using a javascript callback. The other way to handle another site is to have your server proxy the request, i.e., you call a method on your server which, in turn, performs the actual request for you.

If you are accessing the same server, then I'd suggest setting up some server methods to return just the HTML that you want to inject on the page rather than loading and parsing an entire page to get just some elements.

tvanfosson
To clarify, all the pages I'm accessing are on my own server (currently dev box.) The only content wrapping the elements I wish to download and insert are standard <html> and <body> tags, for example. I understand you are saying that even those should be stripped out so that the content I want to insert is the only thing on the page, but I would like to make one call and get back content that I can pull apart, in javascript, and insert at various places, for efficiency.
Matt W