正常重定向或预加载

6

我在网络上找到了几种预加载/重定向网页的方法。

现在问题是,这是否是处理带有预加载的重定向的正确方式(异步加载下一页,同时仍显示当前页面)。

$.get("page.php", function (data) {
    document.open();
    document.write(data);
    document.close();
    window.history.pushState("Title", "Title", "/page.php");
    $.cache = {};
}, "html");

我应该选择普通重定向还是其他方式更好?
window.location = "page.php";

下一页包含全屏视频和声音轨道(音频)。
谢谢。

你可以使用 Ajax:https://en.wikipedia.org/wiki/Ajax_(programming) 来异步加载下一页! - Behzad
有用的链接:http://www.w3schools.com/json/json_http.asp - Behzad
1个回答

4
你可以使用 Ajax 异步加载下一页。这里是一个使用 GET 方法编写的简单 Ajax 请求示例,使用 JavaScript

AJAX 代表异步 JavaScript 和 XML,为了使 XMLHttpRequest 对象行为像 AJAX,open() 方法的 async 参数必须设置为 true:xhr.open('get', 'send-ajax-data.php', true);

get-ajax-data.js:

// This is the client-side script.

// Initialize the Ajax request.
var xhr = new XMLHttpRequest();
xhr.open('get', 'send-ajax-data.php', true); // `true` makes the request asynchronous

// Track the state changes of the request.
xhr.onreadystatechange = function () {
    var DONE = 4; // readyState 4 means the request is done.
    var OK = 200; // status 200 is a successful return.
    if (xhr.readyState === DONE) {
        if (xhr.status === OK) {
            alert(xhr.responseText); // 'This is the returned text.'
        } else {
            alert('Error: ' + xhr.status); // An error occurred during the request.
        }
    }
};

// Send the request to send-ajax-data.php
xhr.send(null);

最后,您可以使用以下代码重新加载或重定向页面数据:

document.getElementById("myDiv").innerHTML = xhr.responseText;

1
这是一些关于浏览器兼容性的额外信息,如果 OP 有兴趣可以查看 http://caniuse.com/#feat=xhr2 - zfrisch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接