Save html in cookie
I am using jquery to clone and append some html into a div.
My problem is that this html will be removed when the page is refreshed. The question is how I can save the appended HTML in the div (the html code will contain some inputs and select lists and there will be plenty of co开发者_运维知识库de).
What should I look into?
Cookies?
HTML5?
Anything else?
If you're only going to support modern browsers I would go for HTML5's offline storage.
Another approach would be to get the AJAX route.
You don't want to use cookies for this, bacause:
cookies get loaded at every request
cookies can only hold limited amount of information.
Use one of plenty jquery storage plugins. Many of them uses html5 storage, but if there is not present support for html5 storage in browser, it will use other techniques. For example with JQUERY STORAGE plugin you would save data in this way:
$.Storage.set("name", "value");
and restore it in this way:
$.Storage.get("name");
If you are appending code to another element, i recommend to save same data you are appending to storage too instead of selecting and getting it from document (it's a bit faster).
you can try to this function
<php
function getVar($name, $def = '') {
if (isset($_REQUEST[$name]))
return $_REQUEST[$name];
else
return $def;
}
// check if overrides passed
$efind = getVar('q', '');
?>
this example for input tag
<input type="text" name="q" onFocus="this.value=''" onBlur="if(this.value == '')this.value ='<?php echo htmlentities($efind); ?>'" value="<?php echo htmlentities($efind); ?>" />
please correct if I make mistakes
Definitely do not try to store HTML in cookies... the size limitation alone 1 would not make this a good option. However you might want to save a "flag" in the cookies that when the page re-renders, triggers the re-insertion of the HTML code (either by re-calling the function that added it the first time, or by pulling it in via AJAX.)
However what I would recommend is that you do an AJAX call back to the server when the user appends content to the page. This call would update the object/database on the server such that when the page is reloaded, it brings back the full content, including the part that was added dynamically by the user.
RFC 2109
[1] RFC 2109 - section 6.3 (on HTTP Cookies)
4096 bytes per cookie
20 cookies per unique host or domain name
Hakan, the ajax call will do your full page cache useless (or at least less useful) cause your server will load the php+apache/nginx for every request again so you won't gain almost any performance, or at least not big as a completely full page cache. We are planing to do a full cache solution and at first attempt we thought in to use cookie and session for shopping cart, asking if the client supports cookie and downgrade to Ajax call otherwise. Tell me if you finally got a solution. I'm planning to use nginx and memcache to full page cache and php + apc + apache + mod_sitespeed for backend requests
精彩评论