【问题标题】:Use jQuery to update URL with value from checkboxes and keep checked after refresh使用 jQuery 使用复选框中的值更新 URL 并在刷新后保持选中状态
【发布时间】:2015-03-10 16:49:33
【问题描述】:

我找到了一个非常棒的 jQuery 脚本,它可以帮助我从作为数组发送到 URL 的复选框中获取值。这工作得很好,但我需要在每次选择后刷新页面,但是通过这样做,在谷歌浏览器中取消选中复选框(在 FF 中工作正常)。 URL 保持正常,但所有复选框都未选中。

在 jQuery 中有什么方法可以在刷新后保持选中的复选框处于选中状态?通常对我来说,当希望在发布或刷新后检查复选框时,我可以在复选框中使用 if 语句,即 if($_GET[selected] == $value){ echo "checked"; }

您可以在这里测试代码:http://mazey.dk/bato/temp.php

代码如下所示:

<?
$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[PHP_SELF]";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Konfigurator</title>
<link rel="stylesheet" href="main.css" />
<style type="text/css">
body,td,th {
    font-family: Tahoma, "Titillium Web", sans-serif;
}
</style>
<script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>

</head>

<body>

     <div class="flowers">
     <?
    $hent_access  = mysql_query("SELECT * FROM bato_produkter WHERE typen = 2");
    while($hent_access_data = mysql_fetch_array($hent_access)){
    $erstat2 = str_replace('BATO','bata',$hent_access_data[navn]);
    ?>
    <div class="flowers">

    <label>
    <table width="100%" border="0" cellspacing="0" cellpadding="0" >
  <tr>
    <td><img src="images/<?=$hent_access_data[vnr]?>.jpg" width="150" class="apply_image" /></td>
  </tr>
  <tr>
    <td class="product_list_header"><?=$erstat2?></td>
  </tr>
  <tr>
    <td  class="product_list_header">kr. <?=$hent_access_data[pris]?></td>
  </tr>
  <tr>
    <td  class="product_list_header"><input type="checkbox" name="selected[]" value="<?=$hent_access_data[vnr]?>" /></td>
  </tr>
</table>
</label>
    </div>
    <?
    }
    ?>
    </div>

<script>
$('input[type="checkbox"]').on('change', function(e){
var data = [],
loc = $('<a>', {href:window.location})[0];
$('input[type="checkbox"]').each(function(i){
if(this.checked){
data.push(this.name+'='+this.value);
}
});
data = data.join('&');
$.post('<?=$actual_link?>', data);
if(history.pushState){
history.pushState(null, null, loc.pathname+'?cart=<?=$_GET[cart]?>&'+data);
location.reload();
}

});
</script>

</body>
</html>

---- 编辑----

在阅读了 cmets 并研究了一段时间后,我现在正尝试通过 jQuery 和 AJAX 调用来完成这一切,因为我认为这是最正确的做法(而且我会学到一些全新的东西)。所以这就是我到目前为止所得到的:

<form action="" method="post">

     <?
    $hent_access  = mysql_query("SELECT * FROM bato_produkter WHERE typen = 2");
    while($hent_access_data = mysql_fetch_array($hent_access)){
        $erstat2 = str_replace('BATO','bata',$hent_access_data[navn]);
    ?>

    <label>
    <table width="100%" border="0" cellspacing="0" cellpadding="0" >
  <tr>
    <td><img src="images/<?=$hent_access_data[vnr]?>.jpg" width="150" class="apply_image" /></td>
  </tr>
  <tr>
    <td class="product_list_header"><?=$erstat2?></td>
  </tr>
  <tr>
    <td  class="product_list_header">kr. <?=$hent_access_data[pris]?></td>
  </tr>
  <tr>
    <td  class="product_list_header"><input type="checkbox" name="selected[]" value="<?=$hent_access_data[vnr]?>" /></td>
  </tr>
</table>
</label>
    <?
    }
    ?>
   </form>

<script>
var data = $("form").serialize(); 
var checked = []

$("input[name='selected[]']:checked").each(function ()
{ 
$.ajax({
        url: "hello.php", 
        type: "POST",
        async: true,
        cache: false,
        data: data, 
        success: function(data){ 
            alert(data) 
        }
    }); 
});
</script>

hello.php 文件如下所示:

<?php
include('../settings.inc.php');

    foreach ($_POST[selected] as $value) {
    $list_valg = mysql_query("SELECT * FROM bato_produkter WHERE vnr = '$value'");
    $list_valg_data = mysql_fetch_array($list_valg);
    $pris += $list_valg_data[pris]; 
    $space_used += $list_valg_data[funktion];
    }

echo $pris." - Space used ".$space_used."<br/>Total Space available ".$vogn_space;

?>

现在我收到了显示结果的警报,但只有当我手动刷新页面 (CTRL+R) 时,它才会为每个选中的复选框加载一个警报框。

现在正在尝试完成的内容,是提醒框,以便在检查复选框时显示hello.php的结果,但只有累计的所有复选框。

----- 编辑-----

现在一切都如我所愿,所以这绝对是完美的! 作为扩展,我还有一件事: 如果您查看该网站 - http://mazey.dk/bato/temp.php

当您使用单选按钮选择第一个项目时,复选框会显示。当您选中一个复选框时,您可以在左上角看到选择的状态以及可用空间。对于带有复选框的产品,它们都需要一定的空间。在视觉上它显示在文本的最后部分(1/3、2/3 或 1/1),但它也存储在每个产品的表行中(存储为整数;1、2、3)。

如果产品空间超过可用空间,你能指导我如何完成产品+复选框被隐藏吗?

非常感谢!

【问题讨论】:

  • 在 HTML5 中,您可以使用 History.pushState() 更改 url 而无需离开页面。请注意大写的 H。如果您可以 ajax 并更改 url,则无需更改页面。为了向后兼容,请使用 History.js。 github.com/browserstate/history.js
  • 是的,但我需要为某些 PHP 重新加载页面 - 如您所见,脚本包含 pushState 可以正常工作,但我也需要复选框在刷新时保持选中状态。
  • 为什么需要刷新页面? PHP 都可以在 ajax 调用中完成,以 json 格式返回数据,并使用 js 或 jQuery 相应更新信息。如果您正在加载页面,为什么还要使用 pushState() 呢?只需使用 window.location 加载页面。这是同一件事。如果您希望您的复选框保持选中状态,您需要向 url 传递一些内容以获取 GET 或发布数据,这些数据将在 POST 中可用。或者只是使用 ajax
  • 有趣的@zgr024 - 我需要来自 URL 的值来创建一个 PHP 循环,该循环检索表中的列 ID,以显示图像并累积价格。如果可以在不刷新的情况下“即时”完成,那将是绝对酷的。你能带我上路吗?

标签: php jquery


【解决方案1】:

您是在页面加载而不是更改事件时迭代选定的框。 您有 2 个选项,一个提交按钮或每次单击复选框时发布。

您提到您希望等到所有复选框都被选中,但除非您有提交按钮,否则脚本永远不会知道用户已完成单击复选框。但是,在这种情况下,根据您的问题,您不需要提交按钮。

以下内容将在打开或关闭复选框时发布所选值。每次操作复选框时都会触发该事件,并且您返回的数据可用于操作表格或返回 HTML。在此示例中,它从 hello.php 将数据作为 HTML 返回,然后将该响应放置在 id 为“result”的 div 元素中

<form action="" method="post">

    **** ADDED FOR NEW QUESTION ****
    <input type="hidden" id="totalSpaces" value="12"> 

<?
    $hent_access  = mysql_query("SELECT * FROM bato_produkter WHERE typen = 2");
    while($hent_access_data = mysql_fetch_array($hent_access)) {
        $erstat2 = str_replace('BATO','bata',$hent_access_data[navn]);
?>

    <table width="100%" border="0" cellspacing="0" cellpadding="0" >
        <tr>
            <td><img src="images/<?=$hent_access_data[vnr]?>.jpg" width="150" class="apply_image" /></td>
        </tr>
        <tr>
            <td class="product_list_header"><?=$erstat2?></td>
        </tr>
        <tr>
            <td class="product_list_header">kr. <?=$hent_access_data[pris]?></td>
        </tr>
        <tr>
            *** EDITED FOR NEW QUESTION ***
            <td class="product_list_header"><input type="checkbox" name="selected[]" value="<?=$hent_access_data[vnr]?>" data-spaces="<?=$hent_access_data['pris']?>" /></td>

        </tr>
    </table>
<?
    }
?>


</form>
<div id="result"></div>   

<script>
    *** ADDED FOR NEW QUESTION *** 
    var totalSpaces = $('#totalSpaces').val();
    var usedSpaces = 0;

    // triggered when user clicks a checkbox
    $('input[name="selected[]"]').on('change',function () { 


        *** ADDED FOR NEW QUESTION ***
        currentSpaces = parseInt($(this).data('spaces');

        if ($(this).is(':checked')) usedSpaces += currentSpaces;
        else usedSpaces -= currentSpaces;

        if (usedSpaces > totalSpaces) {
            alert('Will not fit');
            return false;
        }           


        // grabs the selected checkbox values
        var data = $("form").serialize(); 


        // Sends the data via POST to hello.php
        $.ajax({ 
            url: "hello.php", 
            type: "POST",
            dataType: 'html',
            async: true,
            cache: false,
            data: data,
            success: function(data) { 

                *** ADDED FOR NEW QUESTION ***
                if (usedSpaces == totalSpaces) {
                    alert ('All spaces used');
                    $('input[name="selected[]"]').not(':checked').prop('disabled',true);
                }
                else {
                    $('input[name="selected[]"]').prop('disabled',false);
                }
                $('#result').html(data);
            }
        }); 
    });

</script>

请查看标记为 ADDED 或 EDITED 的编辑

【讨论】:

  • 非常感谢@zgr024 - 当我回到我的电脑时我会试试这个。我开始看到你所解释和展示的结构,所以我非常渴望更熟悉这一点。我稍后再测试 - 再次感谢。
  • 这绝对是完美的!它就像一种魅力,而且我在看到 jQuery 中的逻辑时感觉更好:-) 我会接受你的回答,我真的很感激你帮助我的东西。不过,我还有一个问题,但这与我希望在复选框超过一定大小时隐藏它们有关(我已将其存储在 hello.php 文件的变量中)。在这里发布一个新问题是正确的吗?...再次感谢!
  • 其实最好先问一个新问题或者自己尝试一下。但是将限制放在带有复选框的页面上,而不是放在 php.ini 中。您可以使用表单中的隐藏字段来执行此操作,并将数字放在数据属性中。然后将它们添加到更改事件中。
  • 太棒了@zgr024 - 我已经编辑了我的帖子,所以最后一部分包含了给你的最后一个问题 - 如果你有任何问题,请告诉我,因为我很难解释:- )
  • 请查看我对答案所做的修改。您不应使用该帖子来确定已使用与可用的内容。事实上,我会考虑根本不使用该帖子,因为您可以在没有 PHP 和新查询的情况下操作 html,而是将所需的所有内容放在数据属性中
猜你喜欢
  • 2021-04-24
  • 2021-04-30
  • 2021-05-25
  • 1970-01-01
  • 2020-09-16
  • 1970-01-01
  • 1970-01-01
  • 2011-03-11
  • 2016-05-08
相关资源
最近更新 更多