开发者

jQuery Ajax Render Fragments OR Whole Page

开发者 https://www.devze.com 2023-03-22 06:05 出处:网络
I\'m in the throes of building an application that wraps a mess of legacy code.For the page I am working on, I need to substitute fragment divs constructed on my back-end -- or else I need to replace

I'm in the throes of building an application that wraps a mess of legacy code. For the page I am working on, I need to substitute fragment divs constructed on my back-end -- or else I need to replace the entire page altogether. The idea is that there is a dynamically controlled flow that needs to be satisfied before we can forward to the legacy product.

Substituting fragments works fine, as seen in the below my_body_content swap. The trouble comes when what I'm trying to render is not a fragment, but the whole page, as in the "body" swap. At this point the page goes blank.

I also want to do something similar with errors returned from the server. I want my nice REST 404 error messages to be displayed on the screen, but for legacy-product 404s to show in the legacy-product 404 page.

Yes, the requirements for this project are weird. That's not a problem I can fix.

Here's my jQuery invocation, with names changed to protect the guilty:

    $.ajax({
    url: "places/things",
    type: "POST",
    data: JSON.stringify(someBadAssObject),
    dataType: "text",
    accepts: "text/html",
    contentType: "application/json; charset=utf-8",
    success: function(x) {
        var fragcheck = $("#my_fragment", x);
        if (fragcheck != null && fragcheck.length > 0)
            $("#my_body_content").html(x);
        else
            $("body").html(x);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        error(error开发者_如何学编程Thrown);
        if (XMLHttpRequest.responseText.startsWith("<html>"))
            $("body").html(XMLHttpRequest.responseText);
    }
});


Okay, I think I can answer my own question:

$("body").html(x);

doesn't work, and

$("html").replaceWith(x);

doesn't work, and other permutations along the same idea don't work either.

This works:

document.open();
document.write(XMLHttpRequest.responseText);
document.close();

So the whole solution looks like this:

$.ajax({
url: "places/things",
type: "POST",
data: JSON.stringify(someBadAssObject),
dataType: "text",
accepts: "text/html",
contentType: "application/json; charset=utf-8",
success: function(x) {
    var fragcheck = $("#my_fragment", x);
    if (fragcheck != null && fragcheck.length > 0)
        $("#my_body_content").html(x);
    else
    {
        document.open();
        document.write(x);
        document.close();
    }
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
    error(errorThrown);
    if (XMLHttpRequest.responseText.startsWith("<html>"))
    {
        document.open();
        document.write(XMLHttpRequest.responseText);
        document.close();
    }
}

});

Hope this helps the next poor schmoe!

0

精彩评论

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