-1

我在 php 中有一个 setcookie 函数。我有一个带有输入字段和提交按钮的 jquery 对话框。当我在输入字段中输入邮政编码并推送提交时,邮政编码保存在 php cookie 中。

此 cookie 将显示在主页上的输入字段中。

现在是我的问题,当我没有设置 cookie 时,例如,我将输入字段留空并单击提交它给我一个错误。但在输入字段中。

我正在使用codeigniter,所以这可能是问题所在。

错误:

消息:未定义索引:名称文件名:views/navmenu.php 行号:33

我设置的 cookie 和表单代码:

<div id="dialog" class="hidden" title="Welkom bij OostWestRegioBest.nl">
Vul hier uw postcode in.
<form method="post" action"">
Postcode: <input type="text" name="name" size="25">
<input type="submit" value="Opslaan">
<input type="hidden" name="submitted" value="true">
</form>

<?php
// set the cookie with the submitted user data
setcookie('name', $_POST['name']);
?>

<?php
    if(isset($_POST['Submit']))
    {
    header("location: {$_SERVER['PHP_SELF']}");
    }
?>

</div>

我将在其中显示 cookie 的输入字段。

<input type="text" value='<?php echo $_COOKIE['name'] ?>'>  

希望有人可以帮助我。

谢谢。

4

2 回答 2

1

请仅在提交表单后设置cookie

if(isset($_POST['Submit'])){
     setcookie('name', $_POST['name']);
}

您可以将输入字段更改为

<input type="text" value='<?php echo isset($_COOKIE['name']) ? $_COOKIE['name'] : '' ?>'>
于 2013-03-20T08:21:16.520 回答
1

仅当 $_POST 包含具有索引 - 名称的元素时才设置 cookie。

你可以试试这个。

<?php
    // set the cookie with the submitted user data
    setcookie('name', isset($_POST['name']) ? $_POST['name'] : "");
?>

或者仅当 cookie 包含具有索引 - 名称的元素时才设置 cookie。

<?php
    if (isset($_POST['name'])) {
       // set the cookie with the submitted user data
       setcookie('name', $_POST['name']);
    }
?>

根据您的要求选择任何一种。

于 2013-03-20T08:20:19.710 回答