[英]Cannot get cookie value
我有一個腳本,當我按下按鈕並從用戶那里獲取一個數字時,它會調用一個提示。 該號碼存儲在 cookie 中。 然后該腳本加載一個視圖,該視圖從 cookie 中獲取數字並將其傳遞給表單。
目前我已經保存了 cookie; 我可以在瀏覽器調試器中看到它。 但是當我嘗試在我的視圖中獲取 cookie 時,它總是返回 null。
我認為該請求在更新 cookie 之前發送了一個空值的 cookie。
JavaScript
$(document).ready(function() {
$(document).off('click', '.order_button').on('click', '.order_button', function() {
// $(".on_button").click(function() {
var amount = prompt("Please enter amount of orders" ,"0")
if (parseInt(amount) <= 0 /* || amount === null */) {
alert("Please enter integer greater than 0")
} else if (parseInt(amount) > 0) {
document.cookie = "amount=" + amount; //+ ";max-age=60";
console.log(document.cookie)
var link = $(this).find('a');
console.log(link.attr('href'));
window.location.href=link.attr('href');
console.log("OK");
}
return false;
});
});
看法
def add_order(request, meal_slug, meal_restaurant):
print("OK")
amount = get_server_side_cookie(request, 'amount', '1')
print(amount)
//clear_amount_cookie(request)
if amount is not None:
meal = Meal.objects.get(
slug=meal_slug, restaurant_slug=meal_restaurant)
user = UserProfile.objects.get(user=request.user)
order = Order.objects.create(
meal=meal, customer=user, amount=amount, date=datetime.now())
order.save()
//clear_amount_cookie(request)
return redirect('food_cloud:index')
獲取cookie函數
def get_server_side_cookie(request, cookie, default_val=None):
val = request.COOKIES.get(cookie)
print(val) //This is where I see the null value
try:
int(val)
except (ValueError, TypeError):
val = default_val
print(val + " here")
return val
我通過實現 jquery.cookies.js 對象解決了這個問題鏈接: https : //github.com/carhartl/jquery-cookie
然后我替換了創建 cookie 的代碼。 顯然 JQuery 不適合直接處理 cookie
更改代碼
$(document).ready(function() {
$(document).off('click', '.order_button').on('click', '.order_button', function() {
var amount = prompt("Please enter amount of orders" ,"0");
if (parseInt(amount) <= 0 /* || amount === null */) {
alert("Please enter integer greater than 0")
} else if (parseInt(amount) > 0) {
Cookies.set('amount', amount) //This is the new code for creating cookie
console.log(document.cookie)
var link = $(this).find('a');
console.log(link.attr('href'));
window.location.href=link.attr('href');
console.log("OK");
}
return false;
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.