1

I have an AJAX request that grabs the source of Wikipedia pages:

$.ajax({
    url: "TrollWikipedia.ashx",
    data: {
        url: "http://en.wikipedia.org/wiki/20s",
    },
    type: "GET",
    success: function (html) {
        var page = $(html);
        alert(page.find("#content").length); //Alerts 0
        alert(page.html()); //alerts null
    }
});

It successfully returns the source of the page (I have a copy of the string it returns here on jsFiddle).

The problem: I can't seem to make a jQuery object from the HTML (like they do here). For some reason, it doesn't seem to be creating the object correctly. What am I doing wrong?

Community
  • 1
  • 1
Peter Olson
  • 139,199
  • 49
  • 202
  • 242
  • I'd imagine the jQuery regex determining if the value is HTML is failing somehow. Is the HTML coming from Wikipedia properly formed? Alternatively, you could always stuff that in a ` – Tejs Aug 10 '11 at 20:51
  • @Tejs You can inspect the jsFiddle link and see if the HTML is properly formed. – Peter Olson Aug 10 '11 at 20:52

2 Answers2

1

html data seems to be badly parsed (maybe a closing div tag is missing in the html code), use:

$.ajax({
    url: "TrollWikipedia.ashx",
    data: {
        url: "http://en.wikipedia.org/wiki/20s",
    },
    type: "GET",
    datatype: "html",
    success: function (html) {

        html=html.replace(/(<body [^>]*>)/i, '$1<div>').replace(/(<\/body>)/i, '</div>$1');
        var page = $(html);
        alert($("#content",page).length); //Alerts 1
        alert(page.html()); //alerts html
    }
});
Darm
  • 5,581
  • 2
  • 20
  • 18
0

html string contains the links pointing to en.wikipedia.org site, so when we do $(html) jQuery might be getting exception due to cross domain script calls inside the html markup due to which you are not getting any thing after $(html)

ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124