简体   繁体   English

Ajax发布到php。 保存cookie并将其发送回javascript

[英]Ajax post to php. Save cookie and send it back to javascript

I am sending data to php via ajax POST. 我通过ajax POST发送数据到php。 I want to save it in a php cookie, and then be able to retrieve it in javascript via a ajax GET request. 我想将其保存在php cookie中,然后能够通过ajax GET请求在javascript中检索它。 In PHP, my cookie check function is returning "cookie ____ is not set". 在PHP中,我的cookie检查函数返回“未设置cookie ____”。 What am I doing wrong that is causing me not being able to store my cookie, and then retrieve it. 我做错了什么,导致我无法存储Cookie,然后无法检索它。

AJAX POST AJAX POST

function(config) {
    var config_copy = JSON.parse(JSON.stringify(config));

    //post cookie
    $.ajax({
           url: "php/pivot_cookie.php",
           type: "POST",
           data: config_copy,
           success: function(){ alert("Cookie: success") },
           error: function(data){alert(data);}
     });

}

PHP PHP

$cookie_name = "pivot_config";
$cookie_value = $_POST['config_copy'];
setcookie($cookie_name, $cookie_value, "/");

//cookie check function
if(!isset($_COOKIE[$cookie_name])) {
    echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
    echo "Cookie '" . $cookie_name . "' is set!<br>";
    echo "Value is: " . $_COOKIE[$cookie_name];
}

AJAX GET I dont know what I put in the "data" field to retrieve the cookie so I can pass it into one of my other functions AJAX GET我不知道我在“数据”字段中输入了什么来检索Cookie,因此我可以将其传递给其他功能之一

 $(document).ready(function(){
    $.ajax({
          url: "php/pivot_cookie.php",
          type: "GET",
          data: (cookie - I dont know how to get it),
          success: function(){ alert("Cookie Retreival: success") },
          error: function(data){alert("Cookie Retrieval: failure");}
    });
}

You are not setting a correct expiry on your cookie. 您没有为Cookie设置正确的有效期。 Try: 尝试:

setcookie($cookie_name, $cookie_value, time() + 3600, "/"); // expire in 1 hour

see official docs for setcookie 查看setcookie的官方文档

Aside from not giving PHPs setcookie() what it wants for a 3rd parameter you also needed to set one parameter for $.ajax() 's .success() method. 除了不给PHPs setcookie()提供第3个参数所需的内容外,您还需要为$.ajax().success()方法设置一个参数。

After that you can make .success(data) handle the data however you want. 之后,您可以使.success(data)处理所需的data

Note the JSON data I am passing in place of the data property in the ajax-post.html file. 请注意 ,我要传递的JSON数据代替ajax-post.html文件中的data属性。

data: {"config_copy": config_copy}

Depending on the data you're handling you could just use Javascript to retrieve the cookie data. 根据您要处理的数据,您可以只使用Javascript检索Cookie数据。

Try the below inside your web browser's Console? 在网络浏览器的控制台中尝试以下操作? After you've set the cookie ( assuming you set only the one cookie pivot_config ) 设置cookie之后(假设您仅设置了一个pivot_config

escape( document.cookie.split('=').pop() ).replace('+', ' ')

Also to note cookies are limited in the amount of data they can store. 还要注意,Cookie可以存储的数据量有限。

pivot_cookie.php pivot_cookie.php

$cookie_name = "pivot_config";

if ( isset( $_POST['config_copy'])) {
    $cookie_value = $_POST['config_copy'];
    setcookie($cookie_name, $cookie_value, time()+3600, "/");

    //cookie check function
    if(!isset($_COOKIE[$cookie_name])) {
        echo "Cookie named '" . $cookie_name . "' is not set!";
    } else {
        echo "Cookie '" . $cookie_name . "' is set!<br>";
        echo "Value is: " . $_COOKIE[$cookie_name];
    }
}
else {
  if ( isset( $_COOKIE[$cookie_name] ) ) {
    echo $_COOKIE[$cookie_name];
  }
}

ajax-post.html Ajax的post.html

<html>
<head>
  <title>getting using ajax</title>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  <script>
  function x (config) {
    var config_copy = JSON.parse(JSON.stringify(config));

    //post cookie
    $.ajax({
            url: "pivot_cookie.php",
            type: "POST",
            data: {"config_copy": config_copy},
            success: function(data,b,c){
              alert("Cookie Retreival: success");
              $("body").html(data);
            },
            error: function(data){alert(data);}
        });

    }

    window.addEventListener("load", function () {
        x("hi post");
    });
  </script>
</head>
<body>
</body>
</html>

ajax-get.html Ajax的get.html

  <html>
  <head>
    <title>getting using ajax</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
      $.ajax({
          url: "pivot_cookie.php",
          type: "GET",
          data: "(cookie - I dont know how to get it)",
          success: function(data,b,c){
            alert("Cookie Retreival: success");
            $("body").html(data);
          },
          error: function(data){alert("Cookie Retrieval: failure");}
      });
    });
    </script>
  </head>
  <body>
  </body>
  </html>

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

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