Stephen Collins Stephen Collins - 6 months ago 35
HTML Question

Parsing returned HTML from jQuery AJAX request

What I'm trying to do seems simple: get an HTML page through

$.ajax()
and pull out a value from it.

$(function () {
$.ajax({
url: "/echo/html",
dataType: "html",
success: function (data) {
$('#data').text(data);
$('#wtf').html($(data).find('#link').text());
},
data: {
html: '<!DOCTYPE html><head><title><\/title><link href="../css/popup.css" rel="stylesheet" /><\/head><body><ul><li><a id="link">content<\/a><\/li><\/ul><\/body><\/html>'
}
});
});


The problem is that jQuery refuses to parse the returned HTML.

The fiddle I'm play with this in isn't working in the mean time, so there's little else I can do to provide a working example.

UPDATE: My new fiddle is working fine, but it seems the problem is that in my actual project I'm trying to parse a large, complex bit of HTML. Is this a known problem?

Answer

Your code works fine. You just aren't using jsFiddle's API correctly. Check the docs for /echo/html/ (http://doc.jsfiddle.net/use/echo.html#html):

URL: /echo/html/

Data has to be provided via POST

So, you need to update your AJAX call to use POST. Also the trailing slash is needed.

$(function () {
    $.ajax({
        url: "/echo/html/",
        type: "post",
        dataType: "html",
        success: function (data) {
            $('#data').text(data);
            $('#wtf').html($(data).find('#link').text());
        },
        data: {
            html: '<!DOCTYPE html><head><title><\/title><link href="../css/popup.css" rel="stylesheet" /><\/head><body><ul><li><a id="link">content<\/a><\/li><\/ul><\/body><\/html>'
        }
    });
});

DEMO: http://jsfiddle.net/hcrM8/6/

Comments