因為在做註冊頁面,點擊註冊按鈕完成以下任務:
①把得到的註冊資訊,通過後台添加到資料庫中,
②在前台顯示“註冊成功”,
③在註冊的名字,性別寫進cookie中
剛開始想著所有的東西都在後台完成,但是發現一個問題,在後台產生的cookie是在頂層網域中的,我做的在次層網域中,需要後台修改,尋找了不少資料但是無法成功。
後台代碼如下:
//設定條件Cookie
private void SetWhereCookie(string where)
{
HttpCookie cookie = new HttpCookie("username");
cookie.Value = where;
cookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(cookie);
}
protected void Button1_Click(object sender, EventArgs e)
{
username = TextBox1.text;
SetWhereCookie(username );
Response.Write("<script> if (confirm('註冊成功,您將前往首頁進行登入!')) window.location.href='./Homepage.aspx';</script>");
}
但是遇到前端寫的cookie就可以在domain中直接帶著次層網域,而後台寫的卻不可以。
前台產生的cookie檔案
sex
2
localhost/jingsystem/
1600
1488151808
30066602
237686608
30066552
*
username
sssssaaaqw
localhost/jingsystem/
1600
88282624
30066606
3136544720
30066555
*
後台產生的cookie檔案
sex
2
localhost/
1600
1488151808
30066602
237686608
30066552
*
username
sssssaaaqw
localhost/
1600
88282624
30066606
3136544720
30066555
*
找到了一種解決辦法,在背景cookie代碼中添加path來控制cookie.Path="/jingsystem/",總算把這個問題解決。
還有一套解決方案是,前台寫好方法,後台來調用。
前端代碼如下:
function SetCookie(name,value)//兩個參數,一個是cookie的名子,一個是值
{
var Days = 0.25; //此 cookie 將被儲存 30 天
var exp = new Date(); //new Date("December 31, 9998");
exp.setTime(exp.getTime() + Days*24*60*60*1000);
document.cookie = name + "="+ escape (value) + ";expires=" + exp.toGMTString();
}
function writeCookie()
{
alert("hehe");
SetCookie ("username", document.getElementById ("textusername").value);
var obj = document.getElementsByName(RadioButtonList1);
for(i = 0; i <obj.length;i++)
{ if(obj[i].checked) SetCookie ("sex",i);
}
}
後台代碼:
protected void Button1_Click(object sender, EventArgs e)
{
username = TextBox1.text;
ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>writeCookie();if (confirm('註冊成功,您將前往首頁進行登入!')) window.location.href='./Homepage.aspx';</script>");
Response.Write("<script> if (confirm('註冊成功,您將前往首頁進行登入!')) window.location.href='./Homepage.aspx';</script>");
}
又遇見前一句不執行問題,所以只好修改後台代碼如下:
ClientScript.RegisterStartupScript(ClientScript.GetType(), "myscript", "<script>writeCookie();if (confirm('註冊成功,您將前往首頁進行登入!')) window.location.href='./Homepage.aspx';</script>");
終於搞定!
還有幾個問題存在著疑惑:
①為什麼前端寫的cookie就可以在domain中直接帶著次層網域,後台寫的必需得加上path。
②ClientScript.RegisterStartupScript與response.write前後兩句寫,前面不執行。
此外推薦三篇在解決問題中找到的好文章:
某位高手寫的後台一個很實用的類:http://blog.csdn.net/zhoufoxcn/archive/2008/04/21/2312440.aspx
伺服器調用前台代碼的總結文章:http://www.cnblogs.com/lhuser/articles/1458825.html
asp.net中js與c#為互相訪問:http://www.cnblogs.com/ywqu/archive/2009/01/08/1371483.html
有關cookie的屬性講解 http://www.webdn.com/web_file/program/asp/N0610925/