问题
How to get saved value from browsers in jquery,Im Using this script.
require(['jquery', 'jquery/jquery.cookie', 'jquery/ui'], function($){
setTimeout(function(){
console.log($('input#email').val());
var subjectLength = $('#email').val().length;
if(subjectLength > 0) {
console.log('Value Available');
} else {
console.log('Value not Available');
}
}, 3000);
});
回答1:
It looks like you are trying to write to or update a cookie via JavaScript in Magento. You could also do this with PHP using Session or Cookies too. Since you said 'from browser' I am assuming you want a JavaScript solution.
Basically, you will have a Setter and Getter function to set the name, value, and expiration of a cookie and then a function to get the value from a specifically named cookie. Sometimes you might have a clear or delete function too that basically sets he cookie to expire in the past.
I found the following which will help you: https://magento.stackexchange.com/questions/163345/magento-2-how-to-use-cookie
require(['jquery', 'jquery/jquery.cookie', 'jquery/ui'], function($){
setTimeout(function(){
console.log($('input#email').val());
var subject = $('#email').val();
var date = new Date();
var minutes = 60;
date.setTime(date.getTime() + (minutes * 60 * 1000));
if($.cookie('subject').length) {
console.log('Updating Cookie Value: "subject", "' + subject + '"');
$.cookie('subject', subject, {path: '/', expires: date});
} else {
console.log('Setting Cookie Value: "subject", "' + subject + '"');
$.cookie('subject', subject, {path: '/', expires: date});
}
}, 3000);
});
You can expand on this with your own functions if you plan to do it a lot.
function setCookie(k, v, e){
var check_cookie = $.cookie(k); // Get Cookie Value
var date = new Date();
var minutes = e || 60;
date.setTime(date.getTime() + (minutes * 60 * 1000));
if(check_cookie.length){
$.cookie(k, '', {path: '/', expires: -1});
}
$.cookie(k, v, {path: '/', expires: date});
}
function getCookie(k){
return $.cookie(k);
}
function deleteCookie(k){
$.cookie(k, '', {path: '/', expires: -1});
}
Hope that helps.
来源:https://stackoverflow.com/questions/56503795/get-saved-value-from-browsers