简体   繁体   中英

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?

Example: After pressed ok button, the client-side will call Ajax and Ajax will call to PHP server-side to collect data. It will also assign a value into cookies in PHP server-side while it's getting the data. 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.

I tried this many time, but seem like the function can only get the updated cookie's value after the Ajax process is completed.

How would you be able to read a cookie on the client before it has arrived there?

  1. you make an (ajax, or otherwise) request to the server
  2. the server assembles a response, adding a cookie to it
  3. the client receives the response
  4. after the response is there, it can examine the cookie value

To me your question sounds like you try to read the cookie right in step 1. This won't be possible.

If that's not what you are trying to do, then your question needs some re-wording. :)

Cookies exist only on the client side. They're included with each HTTP request, allowing the server to perform actions on them. Javascript can set these cookies for you if you need:

// 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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