我正在制作一个小脚本来改变使用PHP和Ajax/jQuery的网站语言。我希望页面内容刷新而不重新加载页面。到目前为止,我已经设置了
$( "a[data-request]" ).click(function() {
var xhr = new XMLHttpRequest();
var request = $(this).attr('data-request');
var what = $(this).attr('data-to');
xhr.open('GET', '{{ site_url }}' + what + '/' + request);
xhr.onload = function() {
if (xhr.status === 200) {
$("#body").load(location.href + " #body");
}
};
xhr.send();
});
点击链接
<a data-request="english" data-to="home/language" href="#">
它在后台成功执行uri请求并"重新加载"#body元素,这是整个body
<body id="body">
然而,而不是重新加载整个页面内容只是消失,不会再次出现。我做错了什么?
代替xhr.onload
,因为它不是在所有浏览器中实现的,使用onreadystatechange
代替
xhr.onreadystatechange = function () {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200;
if (xhr.readyState === DONE) {
if (xhr.status === OK)
$("html").html(xhr.response);
}
};
xhr.open('GET', '{{ site_url }}' + what + '/' + request); //<-- note must come after above event handler
注意:这也会擦除你的按钮(你点击获取页面的按钮)。因此,代替body
加载数据在一些div
编辑我猜你的代码是这样的
$(document).ready(function(){
$(langDropdown).change(function(){
//get selected language
//do ajax
});
});
现在假设您更改了lang。西班牙语服务器发送给你一个西班牙语版本所以你从服务器得到的就像
<html>
<head> ....title.....
<script src=....></script> //common libs like jquery etc
<script src=my.js></script> //this would be js contaning above code
</head>
<body>
Esta es una pagina
</body>
</html>
现在当您使用document.write
来放置意大利语页面时,document.ready
不会被调用(为什么?因为它只在实际页面刷新时被调用),所以change
事件处理程序不会绑定lang。选择
解决方案:document.ready
之外的代码肯定会运行,即使通过ajax获取,但我不会建议,而我建议的是任何代码你想运行ajax完成(如事件绑定)后写它document.write
是成功回调/readyState
xhr.onreadystatechange = function () {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200;
if (xhr.readyState === DONE && xhr.status === OK) {
$("html").html(xhr.response);
$(langDropdown).change(function(){
//binding code
});
}
};