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?

2
  • 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 <script type="text/html"> element and try querying from inside that. Just a thought. Commented Aug 10, 2011 at 20:51
  • @Tejs You can inspect the jsFiddle link and see if the HTML is properly formed. Commented Aug 10, 2011 at 20:52

2 Answers 2

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
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Tried it, didn't work. :( Note that dataType is case-sensitive.
what is return by adding: alert(html); ?
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)

2 Comments

I wouldn't have thought that would be the reason. If it is, how would I fix it?
I dont think there is any way to fix it unless you use iframe and load the page inside iframe.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.