I'd really like to take all of the html in a div (contains many other divs, form elements, etc), urlencode it (maybe) and then do an ajax post to a server side handler so that I can save the exact state of what the user is seeing.
I would then like to be able to take that string that I've saved in a database and send it back in response to an ajax call in the future.
Should I use something like the following?
var c开发者_JS百科ontents = escape($('#myDiv').html());
Then do an ajax post operation to a server side handler? Would escape ensure that I am not passing back any special characters that would mess up the ajax call?
Any pointers are appreciated.
You don't have to worry about escaping the data if you're sending it as a POST parameter. If it was a GET, it would actually be appearing in the URI and you would need to make sure everything was escaped.
This is all you really need to do:
$.post('/my_handler', {'html': $('#myDiv').html()}. function(data){
//do something with data
});
Your script responding at /my_handler
will just need to check the 'html' post parameter for that string. For example, if you're using PHP you would just check $_POST['html']
.
I'm using this:
function htmlEncode(value){ return $('< div / >').text(value).html(); }
function htmlDecode(value){ return $('< div />').html(value).text(); }
var contents = htmlEncode($('#myDiv').html());
精彩评论