Tôi có một lớp học để xử lý các biến phiên. Đây là một mẫu kèm theo:Cách nhận giá trị phiên bằng cách sử dụng javascript
namespace General
{
public class Session
{
public Session()
{
}
public static string UserID
{
get { return HttpContext.Current.Session["UserID"] as string ?? String.Empty; }
set { HttpContext.Current.Session["UserID"] = value; }
}
public static string departFlightID
{
get { return HttpContext.Current.Session["departFlightID"] as string ?? String.Empty; }
set { HttpContext.Current.Session["departFlightID"] = value; }
}
public static string returnFlightID
{
get { return HttpContext.Current.Session["returnFlightID"] as string ?? String.Empty; }
set { HttpContext.Current.Session["returnFlightID"] = value; }
}
}
}
Bây giờ tại một số điểm tôi lưu trữ các flightID
trong:
General.Session.departFlightID = flightID;
Và vào thời điểm khác tôi muốn lấy giá trị này sử dụng Javascript. Tôi đã thấy các ví dụ ở đây nhưng chúng sẽ không hoạt động (không có lỗi nhưng chúng sẽ trả về EMPTY
).
gần đây nhất:
var session = '<%= General.Session.departFlightID %>';
var session = '<%= HttpContext.Current.Session["departFlightID"] %>';
Nó làm việc nếu tôi đặt giá trị trên tải trang, nhưng tôi đang chạy một WebMethod mà tôi tạo ra một html và sau đó gửi html lại trở nên thông dụng bên trong một div để làm một vé ở đó. Tôi cần nhận giá trị phiên nhưng không cập nhật.
Để làm cho nó rõ ràng hơn ở đây là mã Javascript:
<script type="text/javascript">
function addTicket(flightID, flightType) {
PageMethods.addTicket(flightID, flightType, OnGetMessageSuccess);
}
function OnGetMessageSuccess(result, userContext, methodName) {
var pageUrl = document.URL;
if (pageUrl.indexOf("&ret_date=&") !== -1) {
var session = '<%= HttpContext.Current.Session["departFlightID"] %>';
alert(session);
result = result + "<a onclick=\"searchflight.abortAllAjax()\" data-index=\"6\" class=\"bookNow\" title=\"Book Now!\" href=\"#\">Book Now!</a>";
result = result + "</div> </div> </div>";
document.getElementById("detail").innerHTML = result;
}
}
Và đây là WebMethod:
[System.Web.Services.WebMethod]
public static string addTicket(string flightID, string flightType)
{
//GET FLIGHT DETAILS FROM DATATABLE OR SESSION DATA TABLE
string tmpHtml = string.Empty;
tmphtml="sample";
string flightID="123123213";
General.Session.departFlightID=flightID;
return tmphtml;
}
bạn đã thử: 'var phiên = '<% = HttpContext.Current.Session [ "departFlightID" ]; %> '; '? – karaxuna
@karaxuna nope nhưng hãy để tôi kiểm tra ... – confusedMind
chỉnh sửa bình luận .. – karaxuna