2016-11-09 45 views
0

我正在編寫一個腳本來改變使用PHP和Ajax/jQuery的網站語言。我希望頁面內容在不重新加載頁面的情況下刷新。到現在爲止我已經使這個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="#"> 

它succesfuly進行背景URI請求和 「重載」 #body元素,它是全身

<body id="body"> 

然而,重新加載整個頁面內容不會消失,而不會再次出現。我究竟做錯了什麼?

回答

0

更換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載荷數據一些分區。

編輯 我想你的代碼是這樣的

$(document).ready(function(){ 

    $(langDropdown).change(function(){ 
     //get selected language 
     //do ajax 
    }); 
}); 

現在,假設你改變郎。西班牙服務器發送你一個西班牙語版本,所以你從服務器得到的是像

<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 
     }); 
    } 
}; 
+0

這工作,但我的目標是重新加載整個頁面,因爲它改變語言。所以如果我只重新加載一個特定的元素 - 其他元素將顯示舊的語言,而特定的元素將以新的語言顯示。 –

+0

我看到了,我已經更新了 – Viney

+0

,這仍然會讓我的html變得有點麻煩。我可能會激活頁面簡單的刷新。但是謝謝你。 –