简体   繁体   English

单击链接时设置会话变量

[英]Set a session variable when a link is clicked

I want to set a session variable to 0 when any of a certain set of links are clicked. 单击某些链接集时,我想将会话变量设置为0。 To do this I have put the following in my javascript file: 为此,我将以下内容放入了我的javascript文件中:

$(window).load(function () {
    $("#hdr li a").click(function () {
        $.ajax({
            type: "POST",
            url: "clear.php",
            data: "width=0"
        });
    });
});

(Ignore data: "width=0"... I don't use this data in clear.php. I put it there because I thought maybe I had to specify a data field.) (忽略数据:“ width = 0” ...我不在clear.php中使用此数据。我将其放在此处是因为我认为可能必须指定一个数据字段。)

and in the file 'clear.php' I simply have: 在文件“ clear.php”中,我仅具有:

<?php session_start();

$_SESSION['name'] = 0;

?>

So, the idea is that when any of the links in #hdr li are clicked, the user should be taken to the page that the link points to, via clear.php, which sets the session variable to 0. 因此,这个想法是,当单击#hdr li中的任何链接时,应该通过clear.php将链接引导至该用户指向的页面,该页面将session变量设置为0。

This works in some browsers (Firefox and Chrome) but not in others (eg, Safari). 这在某些浏览器(Firefox和Chrome)中有效,但在其他浏览器(例如Safari)中无效。

Is this the standard/correct way to implement what I want? 这是实现我想要的标准/正确方法吗? Also, how does the browser know where to go after visiting clear.php? 另外,浏览器在访问clear.php之后如何知道要去哪里? Somehow it works, but my first thought was that I should pass the final destination URL into clear.php, and then use "header" to move from clear.php to the final destination. 它以某种方式起作用,但是我首先想到的是,我应该将最终的目标URL传递到clear.php,然后使用“标头”将clear.php移到最终的目标。

Is Ajax required? 是否需要Ajax? If your re-directing the user to another page & you simply want to pass some data to that page then it may be simpler to include that data in your URL. 如果您将用户重定向到另一个页面,而您只想向该页面传递一些数据,那么将这些数据包含在URL中可能会更简单。

<a href="http://yoursite.com/interesting_page.php?new_session_variable=whatever">Link</a>

Now your php would be simple: 现在您的php很简单:

$_SESSION['name'] = $_GET['new_session_variable'];

Now you've removed your dependency on JavaScript, does that make sense? 现在,您已经删除了对JavaScript的依赖,这有意义吗? :) :)


I feel it might be worth mentioning that your approach would be appropriate in certain situations, for example: if you wanted the user to be able to mark one of the links on the page as a favourite. 我觉得值得一提的是,您的方法在某些情况下是合适的,例如:如果您希望用户能够将页面上的链接之一标记为收藏夹。 Rather than redirecting them to the same page and reloading the majority of the pages content you might: 您可以将它们重定向到同一页面并重新加载大多数页面内容,而不是:

<a class="favourite" data-linkid="link123" href="mylink.php">My Link</a>

// Ensure your page has finished loading aka: 'ready' (almost always)
$(document).ready(function() {

    // Listen for the click event
    $('.favourite').on('click', favoriteLink);

    // On the click - post the update via ajax and update your interface
    function favoriteLink(event) {
        event.preventDefault();

        // Lets get the link id from our data attribute
        var favourite_link = $(this).data('linkid');

        // Post that information via ajax
        $.post('ajax_handler.html', { link : favourite_link }, function(data) {

            // And finally do something with the result!
            $('.result').html(data);
        });
}

My guess is this has something to do with the asynchronicity of AJAX, some browsers are properly firing the AJAX before the new link is loaded. 我的猜测是这与AJAX的异步性有关,某些浏览器在加载新链接之前会正确触发AJAX。 Others might be canceling the AJAX request because the page is changing. 其他人可能正在取消AJAX请求,因为页面正在更改。 Try preventing the default action of the anchor, and then use window.location to redirect them after the ajax call has returned. 尝试阻止锚的默认操作,然后在ajax调用返回后使用window.location重定向它们。

$("#hdr li a").click(function (e) {
    var href = $(this).attr('href');
    e.preventDefault()
    $.post("clear.php", function () {
        window.location = href;
    });
});

The visitor do not get to clear.php page since you are performing an ajax call. 由于您正在执行ajax调用,因此访问者不会进入clear.php页面。

Instead, what happens is that your browser sends a request underneath via javascript using XMLHTTPRequest object which do not break your browser behavior and as such load the page the a href points to. 相反,发生的情况是您的浏览器使用XMLHTTPRequest对象通过javascript在下面发送了一个请求,这不会破坏您的浏览器行为,并因此加载了href指向的页面。

As said : the ajax call is usless. 如前所述:ajax调用是无用的。 You'd better include clear.php on top of your pages and test if whether or not you should set your session var, based on get param for exemple. 您最好在页面顶部包含clear.php,并根据示例获取参数来测试是否应设置会话变量。

If you do want to keep the ajax call before the browser gets to a new page, you may attach an event handler on first common parent of your "resetting" links (event delegation) and test if you should send an ajax request to notify clear.php 如果您确实想在浏览器进入新页面之前保留ajax调用,则可以在“重置”链接(事件委托)的第一个公共父对象上附加事件处理程序,并测试是否应发送ajax请求以通知clear .PHP

I had this problem. 我有这个问题。 I wanted to pass a different sql string to select different rows from a table depending on the link the user clicked on but i did not want to display the sql in a GET. 我想根据用户单击的链接传递不同的sql字符串以从表中选择不同的行,但是我不想在GET中显示sql。

My solution was to set different session variables for each link and pass the NAME of the session variable from the link. 我的解决方案是为每个链接设置不同的会话变量,并从链接中传递会话变量的名称。 I had several links but I have just included 2 here for the example. 我有几个链接,但这里仅包含2个示例。 My code for the links was:- 我的链接代码是:

<?php $_SESSION["extend_stats_sql_01"] = "";                                  
echo '<a href="view_stats_1.php?sort=name&sent=extend_stats_sql_01"> View</a>';}?> <br> 

and

<?php $_SESSION["extend_stats_sql_02"] = " Where booking_status = 'Cancelled'";                               
echo '<a href="view_stats_1.php?sort=name&sent=extend_stats_sql_02"> View</a>';}?> <br> 

My code to retrieve the values on my next page to display the list with the correct sql depending on the link was:- 我的代码用于检索下一页上的值以根据链接显示具有正确sql的列表,其代码为:

$stats_sql = "SELECT id, name, activity, email, diving_date, arrival_date, checkin_date, create_date, seller FROM guests ";
$sort = $_GET['sort']; 
$sent= $_GET['sent'];
$result = $_SESSION["$sent"];
$stats_sql.= "$result"; 
$stats_sql.= " ORDER BY $sort"; 

obviously you need to start a session at the beginning of each page :- 显然,您需要在每个页面的开头开始一个会话:-

session_start(); 

and when you have finished :- 当您完成时:-

// remove all session variables
session_unset();

// destroy the session
session_destroy(); 

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

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