【问题标题】:Setting radio buttons with jQuery while auto-refreshing the page在自动刷新页面时使用 jQuery 设置单选按钮
【发布时间】:2012-02-29 11:42:52
【问题描述】:

我编写了以下 jQuery 用于自动刷新包含投票的页面(以不断更新当前的获胜选项)

function update() {
  var vote_radio = $('input:radio[name=vote_radio]:checked').val();
  $.ajax({
    type: 'POST',
    url: 'index.php',
    data: 'refresh=true&maintain_radio='+ vote_radio,
    timeout: 2000,
    success: function(data) {
      $("#current_body").html(data);
      $("#notice_div").html(''); 
      $("[name=vote_radio]").filter("[value="+vote_radio+"]").attr("checked","checked");
      window.setTimeout(update, 2000);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      $("#notice_div").html('Timeout contacting server..');
      window.setTimeout(update, 60000);
    }
});
};

$(document).ready(update);

在名为“vote_radio”的页面上有一个单选按钮投票,我还使用以下代码来 Ajax 向服务器发送答案:

    $(function() {  
  $('.error').hide();
  $('.failure').hide();
  $('.success').hide();
  $(".vote_submit").click(function() {
        if (!$("input[@name='name']:checked").val()) {
            $('.error').show();
            return false;
        }
        var vote_radio = $('input:radio[name=vote_radio]:checked').val();;
        var dataString = 'vote_radio='+ vote_radio;
        $.ajax({
          type: "POST",
          url: "index.php",
          data: dataString,
          success: function() {
            $('.success').show();               
            $('.failure').hide();               
          },
          error: function() {
            $('.failure').show();               
            $('.success').hide();               
          }
        });
        return false;
  });
});

我遇到的所有问题是,如果用户在页面自动刷新时选择了他们的选项,它会将选定的单选选项恢复到页面开始自动刷新时的状态,这令人沮丧。

另外,如果 .success 类被第二个脚本告知出现,当第一个脚本自动刷新页面时,它会再次隐藏成功类。

【问题讨论】:

    标签: jquery button radio


    【解决方案1】:

    为什么要在启动 AJAX 调用之前将 vote_radio 元素恢复为值?

    只需在覆盖之前读取它,这样您就可以保留当前值(即使它在尚未提交的情况下更改了

    所以只需将成功回调更改为

    success: function(data) {
          var vote_radio = $('input:radio[name=vote_radio]:checked').val();
          $("#current_body").html(data);
          $("#notice_div").empty(); 
          $("[name=vote_radio]").filter("[value="+vote_radio+"]").attr("checked","checked");
          window.setTimeout(update, 2000);
        }
    

    但是,一般来说,正确的方法是只更新页面中需要更新的部分,而不是整个页面。这就是 AJAX 的重点。

    【讨论】:

    • 感谢您的回答。但是,当我替换您的回调函数时,整个函数不会运行。我真正需要做的是继续检查页面是否需要更新,如果需要,则运行 AJAX。页面内容每 120 秒更改一次,您知道如何以某种方式保持时间检查器在后台运行,并在时间低于零时让它调用刷新函数吗?再次感谢。
    猜你喜欢
    • 2012-01-16
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 2014-03-16
    • 1970-01-01
    • 2014-04-10
    • 2019-08-22
    • 2017-07-09
    相关资源
    最近更新 更多