简体   繁体   English

如何使用 Ajax 在 php 服务器端设置 cookie 并使用 Ajax 或 JavaScript 实时读取 cookie?

[英]How can I set cookies in php server-side with Ajax and read cookies in the real time with Ajax or JavaScript?

How can I set cookies in PHP server-side with Ajax and read cookies in the real-time with JavaScript?如何使用 Ajax 在 PHP 服务器端设置 cookie 并使用 JavaScript 实时读取 cookie?

Example: After pressed ok button, the client-side will call Ajax and Ajax will call to PHP server-side to collect data.示例:按下ok按钮后,客户端将调用 Ajax,Ajax 将调用 PHP 服务器端收集数据。 It will also assign a value into cookies in PHP server-side while it's getting the data.它还会在获取数据时为 PHP 服务器端的 cookie 分配一个值。 At the sametime, I want to read the assigned value cookies with another function in real-time(the function will call from the Ajax when it starts calling to PHP server) and display the cookie's value on the client-side.同时,我想用另一个函数实时读取分配值的cookie(该函数在开始调用PHP服务器时会从Ajax调用)并在客户端显示cookie的值。

I tried this many time, but seem like the function can only get the updated cookie's value after the Ajax process is completed.我尝试了很多次,但似乎该函数只能在 Ajax 进程完成后才能获取更新后的 cookie 值。

How would you be able to read a cookie on the client before it has arrived there?您如何能够在客户端上的 cookie 到达之前读取它?

  1. you make an (ajax, or otherwise) request to the server您向服务器发出(ajax 或其他)请求
  2. the server assembles a response, adding a cookie to it服务器组装一个响应,向它添加一个 cookie
  3. the client receives the response客户端收到响应
  4. after the response is there, it can examine the cookie value在响应出现后,它可以检查 cookie 值

To me your question sounds like you try to read the cookie right in step 1. This won't be possible.对我来说,您的问题听起来像是您尝试在步骤 1 中正确读取 cookie。这是不可能的。

If that's not what you are trying to do, then your question needs some re-wording.如果这不是您想要做的,那么您的问题需要重新措辞。 :) :)

Cookies exist only on the client side. Cookie 仅存在于客户端。 They're included with each HTTP request, allowing the server to perform actions on them.它们包含在每个 HTTP 请求中,允许服务器对它们执行操作。 Javascript can set these cookies for you if you need:如果您需要,Javascript 可以为您设置这些 cookie:

// http://www.quirksmode.org/js/cookies.html#script
function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

Take a look at this page discussesComet which seems like what you want.看看这个页面讨论Comet ,它看起来像你想要的。

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

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