简体   繁体   English

在php中刷新时,变量从前一页的querystring中丢失

[英]variable getting lost sent in querystring from previous page on refreshing in php

I have a code in which I'm going from one page to other and passing a variable in querystring. 我有一个代码,我要从一页转到另一页,并在querystring中传递一个变量。 I'm getting that variable in next page and showing the results related to that. 我在下一页获取该变量,并显示与之相关的结果。 But when I refresh the second page, it says the variable which I got from `first page is undefined. 但是当我刷新第二页时,它说我从第一页得到的变量是不确定的。

following is link 以下是链接

<a href="next.php?name=men-shoes">shoes</a>

next.php is as follows next.php如下

$lcSearchVal=$_GET['name'];
<input type="checkbox" name="check" value="one">one<br>
<input type="checkbox" name="check" value="two">two<br>

<script>
$('input[type="checkbox"]').on('change', function(e){
    var data = $('input[type="checkbox"]').serialize(),
        loc = $('<a>', {href:window.location})[0];
    $.post('/ajax-post-url/', data);
    if(history.pushState){
        history.pushState(null, null, loc.pathname+'?'+data);
    }
});
</script>

I'm getting lcSearchVal on second page firstly but when I refresh the page then I'm getting the error in browser that name is undefined index. 我首先在第二页上获得lcSearchVal,但是当我刷新页面时,却在浏览器中看到名称未定义索引的错误。

How to correct this so that when I refresh the page it should be in the same state? 如何纠正此问题,以便在刷新页面时它应该处于相同状态? ie the checkboxes which I have checked should remain checked and lcSearchVal should be read in same way. 即我已选中的复选框应保持选中状态,并且应该以相同方式读取lcSearchVal。

One quick solution would be to make use of sessions. 一种快速的解决方案是利用会话。 So your code would become: 因此,您的代码将变为:

session_start();
if(isset($_SESSION['name']) && ! isset($_GET['name']))
{
   $lcSearchVal = $_SESSION['name'];
}
else
{
    $lcSearchVal = $_GET['name']; // do not forget to sanitize this data
    $_SESSION['name'] = $lcSearchVal;
}

您需要在推送的URL中包含$lcSearchVal

history.pushState(null, null, loc.pathname+'?name=<?php echo urlencode($lcSearchVal) ?>&'+data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM