jQuery Ajax渲染片段或整页

时间:2011-07-20 20:03:47

标签: jquery ajax

我正处于构建包含大量遗留代码的应用程序的阵痛中。对于我正在处理的页面,我需要替换在我的后端构建的片段div - 否则我需要完全替换整个页面。我们的想法是,在我们转发到传统产品之前,需要满足动态控制的流程。

替换片段工作正常,如下面的my_body_content交换所示。当我试图呈现的内容是一个片段,而不是整个页面时,就像在“body”交换中一样。此时页面变为空白。

我还想做一些与服务器返回的错误类似的事情。我希望我的好REST 404错误消息显示在屏幕上,但遗留产品404显示在旧产品404页面中。

是的,这个项目的要求很奇怪。这不是我能解决的问题。

这是我的jQuery调用,更改名称以保护内疚:

    $.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(errorThrown);
        if (XMLHttpRequest.responseText.startsWith("<html>"))
            $("body").html(XMLHttpRequest.responseText);
    }
});

1 个答案:

答案 0 :(得分:3)

好的,我想我可以回答我自己的问题:

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

不起作用,

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

不起作用,同一个想法的其他排列也不起作用。

这有效:

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

所以整个解决方案看起来像这样:

$.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();
    }
}

});

希望这可以帮助下一个可怜的schmoe!

相关问题