在 Global.asax 中设置会话变量会导致 AJAX 错误
我的 asp.net 应用程序遇到了一个非常特殊的问题,我花了很长时间才找到,但我仍然不知道是什么导致了这种行为。
如果我在 Application_PreRequestHandlerExecute
事件中设置会话变量,那么我的外部 JavaScript 文件将被忽略,从而导致大量错误。我将问题简化如下。
例如,
我有一个名为 JScript.js
的文件,其中包含以下代码:
function myAlert() {
alert("Hi World");
}
在我的 Default.aspx
文件中,我使用以下代码引用了 js:
<script src="JScript.js" type="text/javascript"></script>
在正文中 onload< /code> 事件我调用
myAlert()
函数:
<body onload="myAlert()">
最后在 Global.asax
文件中:
Private Sub Application_PreRequestHandlerExecute(ByVal sender As Object, ByVal e As EventArgs)
HttpContext.Current.Session("myVar") = "MyValue"
End Sub
如果运行 Default.aspx
文件你会看到js函数没有被调用,但是,如果你注释掉代码行Global.asax
,那么外部js就会被调用,并且在页面加载时执行该函数。
这是为什么呢?
I'm getting a very peculiar problem with my asp.net application, it took me an age to track down but I still don't know what is causing this behaviour.
If I set a session variable in the Application_PreRequestHandlerExecute
event, then my external JavaScript files are ignored, and therfore causing a raft of errors. I have simplified the problem below.
E.g.
I have file called JScript.js
containing the code:
function myAlert() {
alert("Hi World");
}
And in my Default.aspx
file I reference the js with the code:
<script src="JScript.js" type="text/javascript"></script>
And in the body onload
event I call the myAlert()
function:
<body onload="myAlert()">
And finally in the Global.asax
file:
Private Sub Application_PreRequestHandlerExecute(ByVal sender As Object, ByVal e As EventArgs)
HttpContext.Current.Session("myVar") = "MyValue"
End Sub
If you run the Default.aspx
file you will see the js function isnt called, however, if you comment out the line of code Global.asax
then the external js is called and the function executed when the page loads.
Why is this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
PreRequestHandlerExecute 事件运行两次。一次用于 ASPX 文件,一次用于 JS 文件。当 ASPX 页面请求 JS 文件时运行 PreRequestHandlerExecute 事件时,就会出现此问题。 JS 文件的 Session 为 NULL(或 Nothing),这会导致异常。由于 JS 文件发生异常,因此该文件的内容(您的 myAlert 函数)永远不会加载到 ASPX 页面中。因此,ASPX 页面无法调用 myAlert 函数,因为 JS 文件从未加载。
The PreRequestHandlerExecute event runs twice. Once for the ASPX file and once for the JS file. The problem happens when the PreRequestHandlerExecute event runs when JS file is requested by the ASPX page. Session is NULL (or Nothing) for the JS file which causes an exception. Since an exception occurs for the JS file, the content of this file (your myAlert function) is never loaded into the ASPX page. Therefore, the ASPX page cannot call the myAlert function because the JS file was never loaded.