需要帮助使用$.post()设置cookie值


Need help setting a cookie value with $.post()

我正在运行一个脚本,该脚本将$_COOKIE['menu_item_id']设置为最后一个插入id。我使用jquery的$.post.执行此操作

当post请求使用$.post时,我无法访问应用程序的另一部分中的cookie。我只能在发布请求的同一个php页面中访问它。

我用会话测试了这一点,效果很好,但我不想用会话做这么简单的事情。

为什么我不能通过我的应用程序访问cookie值??

下面是我的代码。

index.php
    $.post("inserNewItem.php", {menu_cat_id : cat_id }
inserNewItem.php
//Preform the insert statment. Get the last_id and assign it to the cookie value "menu_item_id"
$last_id = $db->insert_id;
setcookie("menu_item_id", $last_id);

index.php
//Check if the menu item id has been set after the $.post ajax has been completed 
 if(isset($_COOKIE['menu_item_id'])){
  echo   $_COOKIE['menu_item_id'];
} else {
    echo "cookie is not set"; // I keep getting this 
} 

查看setcookie()的手册。您必须将第4个参数路径作为根/传递。然后cookie将在您的网站的每个部分都可以访问。示例:

setcookie('YourCookie', $value, time()+3600, '/');

记住还要设置过期时间。在上面的示例中,它在一小时后过期。