开发者

jQuery('data') returns html fragment in 'data' with missing data

I make a jQuery get call to fetch a html fragment and do some processing based on that data

$.get($('.more a').attr('href'), function (data) {
        var $data = $(data);
        // other code using $data
    });

Here, 'data' is

<div class="topDiv"> Data goes here </div>

But $data shows as

<div class="topDiv"> </div>

Only the html tags are shown, while the text inside is not. IE has the same problem(?). However, Firefox parse it correctly.

When I alert($(data).html()) , Firefox shows the alert with proper html while chrome and IE show it with the missing text.

Since I am running my project on localhost I am unable to provide a URL for the html fragment.I am using an asp.net ashx handler to provide the html fragment. Basically, when we post a request to the handler, it returns a html fragment based on a query string parameter 开发者_开发技巧passed to it.

String content = "<html> <head> </head> <body>"+
"<div class="topDiv"> Data goes here </div>"+
"</body></html>";

context.Response.ContentType = "text/html";
context.Response.Write(content);

Resolved

As mentioned in the answers, the 'html' fragment was not well formed. Firefox 3 seemed to accept it while Firefox 4, Chrome and IE did not.


I suspect it's because <div>text</div> isn't really a valid html document in itself. IIRC, divs are only supposed to contain block level elements. Text should be inside p, a, etc. So IE and Chrome are killing the text according to DOM standards, Firefox is letting it fly. Tell jQuery the dataType of what you're getting is "text" instead, then insert the content into your div using html(textData) instead.

EG:

$.ajax($('.more a').attr('href'), {
    dataType: 'text'
}).done(text) {
    $('container selector').html(text);
});


How did this:

String content = "<html> <head> </head> <body>"+
"<div class="topDiv"> Data goes here </div>"+
"</body></html>";

ever compile with the unescaped quotes? If you fixed this, you should be rocking and rolling.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜