Javascript 用ajax内容替换当前页面

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4387688/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 12:13:06  来源:igfitidea点击:

Replace current page with ajax content

javascriptjqueryhtmlajax

提问by Bruce

I have a page with a dialog window which sends ajax post data to server and receives a response. During development, there can be two responses - one regular (this is not the question) or one with an error. Server returns code 500 and a page with lot of debug informations. This is a regular page returned from a framework and contains some javascript code. I want to be able to display this error page in case it happens.

我有一个带有对话窗口的页面,该页面将 ajax 发布数据发送到服务器并接收响应。在开发过程中,可能有两种响应——一种是正常的(这不是问题),一种是有错误的。服务器返回代码 500 和包含大量调试信息的页面。这是从框架返回的常规页面,包含一些 javascript 代码。我希望能够显示此错误页面,以防它发生。

The problem is, I can not simply attach the returned result to body element or open a new link in a new page and load this error again. I simply get a html page instead of data and I have to display the page (in current window or in another one).

问题是,我不能简单地将返回的结果附加到 body 元素或在新页面中打开一个新链接并再次加载此错误。我只是得到一个 html 页面而不是数据,我必须显示页面(在当前窗口或另一个窗口中)。

I am using jQuery.

我正在使用 jQuery。

回答by BalusC

Configure jQuery ajax setup as follows:

配置 jQuery ajax 设置如下:

$.ajaxSetup({
    error: handleXhrError
});

where handleXhrErrorfunction look like this:

其中handleXhrError函数如下所示:

function handleXhrError(xhr) {
    document.open();
    document.write(xhr.responseText);
    document.close();
}

See also:

也可以看看:

回答by David Tang

In your ajax callback:

在您的 ajax 回调中:

success: function (data) {
   $("html").html($(data).find("html").html());
}

That will replace the entire page's HTML content with the one received from your AJAX request. Works in Chrome... not sure about IE.

这会将整个页面的 HTML 内容替换为从您的 AJAX 请求中收到的内容。在 Chrome 中工作...不确定 IE。

Despite that, I'm not sure why you'd want to include the <head>section... but you can easily modify the above to display just what's in the body of the AJAX response, and append it to a div or even a lightbox. Much nicer.

尽管如此,我不确定您为什么要包含该<head>部分……但是您可以轻松修改上述内容以仅显示 AJAX 响应正文中的内容,并将其附加到 div 甚至灯箱中。好多了。

回答by Calmarius

You may also try to use data URL's, the latest versions of the major browsers supporting it:

您也可以尝试使用数据 URL,支持它的主要浏览器的最新版本:

function utf8_to_b64( str ) {
    return window.btoa(unescape(encodeURIComponent( str )));
}

function loadHtml(html)
{
    localtion.href='data:text/html;base64,'+utf8_to_b64(html);
}

This way, you can load any html page you want in runtime.

这样,您可以在运行时加载您想要的任何 html 页面。

回答by Aviad

Here is an example of how to change either if the response is a url or a html content (using django\php)

这是一个如何更改响应是 url 或 html 内容的示例(使用 django\php)

        var xmlhttp;
        xmlhttp=new XMLHttpRequest();

        xmlhttp.onreadystatechange=function()
        {
            var replace_t = '{{ params.replace_t }}';
            if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                if(replace_t == 'location')
                    window.location.replace(xmlhttp.responseText);
                else if(replace_t == 'content')
                {
                    document.open();
                    document.write(xmlhttp.responseText);
                    document.close();
                } 
            }
        }

        xmlhttp.open("GET",SOME_ASYNC_HANDLER_URL,true);
        xmlhttp.send();

回答by Bruce

I found this solution. I don't know if it si correct, but for Opera and Firefox it is working.

我找到了这个解决方案。我不知道它是否正确,但对于 Opera 和 Firefox,它是有效的。

var error_win = window.open(
   '',
   'Server error',
   'status=0,scrollbars=1, location=0'
);
error_win.document.write(XMLHttpRequest.responseText);

回答by Shane Tomlinson

Have you tried just simply creating an element and inserting the returned error page into the element? I do this with error pages and jQuery.

您是否尝试过简单地创建一个元素并将返回的错误页面插入该元素?我用错误页面和 jQuery 来做到这一点。

    var errorContainer = $( '<div/>' );
    errorContainer.html( errorTextResponse );
    errorContainer.appendTo( $( 'body' ) );

回答by Mason Stewart

I may be misunderstanding, but do you know what elements from the result you specifically want to display? You could trying something like this:

我可能会误解,但是您知道您特别想要显示的结果中的哪些元素吗?你可以尝试这样的事情:

  success: function(data){
               //store the response
               var $response=$(data);
               //use .find() to locate the div or whatever else you need
               var errorMessage = $response.find('#warning').text();
               alert(errorMessage);      
            }

Is that what you were looking for?

这就是你要找的吗?

回答by user4466133

Just figured this out as easy as

就这么简单地想通了

document.body.innerHTML = YourAjaxrequest.responseText;

_______________________________________________^ up here is what over writes your current HTML page with the response.

_________________________________________________________^ 这里是用响应覆盖当前 HTML 页面的内容。

request.onreadystatechange = function() {
      if (request.readyState == 1) {
        document.getElementById('sus').innerHTML = "SENDING.......";
    } 
      if (request.readyState == 3){
        document.getElementById('sus').innerHTML = "SENDING >>>>>>>>>>>>>";

    }

     if (request.readyState == 4 && request.status == 200) {

        //document.getElementById('sus').innerHTML = request.responseText;

    document.body.innerHTML = request.responseText;


     }
  }
   request.send(formD);



  },false);

回答by mqsoh

I don't think there's any way to do that. Iframes are meant for loading other pages and there's no other sandbox in which to dump a standalone page -- that's what frames were designed for.

我认为没有办法做到这一点。iframe 用于加载其他页面,没有其他沙箱可以在其中转储独立页面——这就是框架的设计目的。

It might be difficult with the framework you're using, but it's probably worthwhile to have it generate different errors for your Ajax requests. My Ajax pages will only ever send

您正在使用的框架可能很困难,但让它为您的 Ajax 请求生成不同的错误可能是值得的。我的 Ajax 页面只会发送

{"exit": 1, "message": "As in the shell, a non-zero exit is an error and this is why..."}