【问题标题】:jQuery reloading incorrectlyjQuery重新加载不正确
【发布时间】:2016-11-09 15:12:35
【问题描述】:

我正在制作一个小脚本来使用 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 id="body">

但是,不是重新加载整个页面内容,而是消失并且不会再次出现。我做错了什么?

【问题讨论】:

    标签: javascript php jquery html ajax


    【解决方案1】:

    替换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
        });
    });
    

    现在假设您更改了语言。 to Spanish server 会向您发送西班牙语版本,因此您从服务器获得的内容有点像

    <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 成功之后编写它回调/就绪状态

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

    【讨论】:

    • 这可行,但是我的目标是在更改语言时重新加载整个页面。所以如果我只重新加载某个元素 - 其他元素将显示旧语言,而特定元素将显示新语言。
    • 这仍然使我的 html 有点混乱。我可能会坚持页面简单的刷新。但谢谢。
    • 告诉我问题,试试document.write()而不是$('html').html()
    • document.write() 适用于第一次更改 - 新语言显示。但是如果我再次尝试切换语言 - 页面不会刷新,语言不会更新。仅在手动刷新时显示新语言
    • 在 ajax 中响应您要发送的新页面的哪一部分?我的意思是只是身体或包括&lt;html&gt;&lt;head&gt; 在内的所有内容?
    猜你喜欢
    • 1970-01-01
    • 2015-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多