【发布时间】:2012-04-21 13:11:31
【问题描述】:
我目前正在使用 PHP 中的一个应用程序,我需要在其中维护一个购物车。一切正常。
当一个项目被添加到购物车时,我需要在 每个页面的标题上显示一条消息,例如“购物篮中有 1 个项目”,如果购物车包含一件商品。
当添加(或删除)其他商品时,消息应该会相应更改无需刷新页面,例如“购物篮中有 2 件商品”等等。
我面临的问题是,当某些商品被删除或添加到购物车时,我需要刷新页面(然后只有这样我才能在页面的标题上看到更新的商品)
例如,假设购物车现在包含 2 件商品,现在又添加了一件商品,标题上的消息仍将显示“购物篮中有 2 件商品” ”,而不是在页面刷新之前显示“购物篮中有 3 件商品”。
在 Java 中,SessionListener 如下所示。
package sessionListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
@WebListener()
public class SessionListener implements HttpSessionListener
{
private HttpSession session=null;
@Override
public void sessionCreated(HttpSessionEvent se)
{
session=se.getSession();
//Use this session
}
@Override
public void sessionDestroyed(HttpSessionEvent se)
{
}
}
我可以使用sessionCreated() 方法来满足要求,因为它是在首次创建会话时只执行一次的方法。
在 .NET 中类似,我们有 Global.asax 应用程序文件,例如
<%@ Application Language="C#" %>
<script runat="server">
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
}
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Session.Add("Message", SomeValue);
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the sessionstate mode
// is set to InProc in the Web.config file. If session mode is set to StateServer
// or SQLServer, the event is not raised.
Session.Abandon();
}
</script>
我可以使用void Session_Start(object sender, EventArgs e) 方法来满足要求,因为这是在会话开始时只调用一次的方法(每个用户的会话一次)。
但是在 PHP 中,我找不到在创建新会话时只执行一次的类似概念(我现在没有使用 PHP 中的任何框架)。
如果是这样,当购物车状态更新而根本没有刷新页面时,如何在每个页面的标题上显示上述指定消息?
【问题讨论】: