Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

javascript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...