在AJAX请求设置一个cookie? [英] Setting a cookie in an AJAX request?

查看:198
本文介绍了在AJAX请求设置一个cookie?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我验证使用jQuery AJAX调用PHP中的登录表单。在PHP中,我创建一个会话,如果他们检查了记住我复选框,我想创建一个cookie。这里的PHP code:

I'm validating a login form with jQuery AJAX call to PHP. In php, I create a session and if they checked the 'remember me' checkbox, I want to create a cookie. Here's the php code:

<?php

include '../includes/connection.php';
date_default_timezone_set('GMT');

$name = $_POST['username'];
$pass = $_POST['password'];


$query = mysql_query("SELECT id, username, password FROM users WHERE username = '$name' LIMIT 1");

if(mysql_num_rows($query) == 0) {
 echo 'error';
 exit;
}

while($row = mysql_fetch_array($query)) {

 if($row['username'] == $name && $row['password'] == $pass) {

  session_start();
  $_SESSION['username'] = $row['username'];
  $_SESSION['usrID'] = $row['id'];
  echo 'success';


  if($_POST['remember']) {
   setcookie('username', $row['username'], $exp);
   setcookie('password', $row['password'], $exp);
   setcookie('usrID', $row['id'], $exp);
  }

 } else {
  echo 'error';
  exit;
 }



}


?>

会话设置成功,但是cookie不会设置的。我试着将所有的值(域,路径等),但这并没有改变任何东西。有什么明显我失踪?

The session is set successfully, however the cookie is not set at all. I've tried setting all the values (domain, path, etc.) but that didn't change anything. Is there anything obvious I'm missing?

推荐答案

下面是一些建议:

  • 请确保您指定日期的正确的到期格式
  • 在设置页面重定向,饼干必须调用标题(位置:...)后才能进行设置上的cookie; 例如:

头('位置:http://www.example.com/'); setCookie方法(asite',$网站,时间()+ 60 * 60,'/','site.com');

header('Location: http://www.example.com/'); setcookie('asite', $site, time()+60*60, '/', 'site.com');

如果您有人类的网址像 www.domain.com/path1/path2 / ,则必须设置cookie路径为/工作的所有路径,不只是当前的。

If you have human urls like www.domain.com/path1/path2/, then you must set cookie path to / to work for all paths, not just current one.

的setcookie('TYPE_ID',$ new_type_id,时间()+ 60 * 60 * 24 * 30,'/');

注意最后 / 中的参数。

从PHP手册:

在服务器上的路径,其中所述   cookie将被提供。如果设置为   /时,cookie将可   在整个域。如果设置为   /富/时,cookie将只   在/富/目录中可用   和所有子目录如   /富/酒吧/域。默认   值是当前目录   该cookie被设置

The path on the server in which the cookie will be available on. If set to '/', the cookie will be available within the entire domain . If set to '/foo/', the cookie will only be available within the /foo/ directory and all sub-directories such as /foo/bar/ of domain . The default value is the current directory that the cookie is being set in.

  • 的setcookie()定义一个cookie随HTTP标头的其余部分被发送。像其他头,饼干必须在任何输出之前,你的脚本意味着不应该有任何的HTML / code回声之前的语句发送。

  • setcookie() defines a cookie to be sent along with the rest of the HTTP headers. Like other headers, cookies must be sent before any output from your script meaning there should be no html/code echo statements before that.
  • 这篇关于在AJAX请求设置一个cookie?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆