问题
I am using AJAX to load the content of a div into another div in another page. After that I am manipulating the history and changing the URL using HTML5 History Api as specified in http://diveintohtml5.info/history.html.
Now the problem occurs when someone clicks the browser back/forward button. I need to load the content of the required div again on the target div. But instead of the content of the required div, the whole content of that page to which the required div belong is being displayed. Again on clicking back/forward button of browser, then if some page contain values appended in the URL then such values in the URL are not getting passed to the required page.
Here is the code that I am using to load the content of a div into another div of other page and manipulate the history and change the URL
function next(type,page)
{
var strURL = "next.php?type="+type+"&pn="+page;
$("#div1").load(strURL+" #div2");
history.pushState(null,null,strURL);// to change URL and history
}
Now for managing back/forward browser button clicks
function navigate(href) {
var req = new XMLHttpRequest();
req.open("GET", "http://localhost/"+href.split("/").pop(),false);
req.send(null);
if (req.status == 200) {
document.getElementById("div1").innerHTML = req.responseText;
return true;
}
return false;
}
window.addEventListener("popstate", function(e) {
navigate(location.pathname);});
}
Could you please help me as I am unable to solve it. Thanks a lot in advance to everyone.
回答1:
After some tricks tried finally I have solved my own question.
Here is the answer to my own question-
function navigate(href) {
var req = new XMLHttpRequest();
req.open("GET", "http://localhost/"+href.split("/").pop(),false);
req.send(null);
if (req.status == 200) {
document.getElementById("div1").innerHTML = req.responseText;
$("#div").load(" #div").hide().fadeIn(1000); //changes done here
return true;
}
return false;
}
window.addEventListener("popstate", function(e) {
navigate(location.pathname);});
e.preventDefault(); //changes done
}
来源:https://stackoverflow.com/questions/59823848/handling-browser-back-forward-for-pages-loaded-using-ajax