几天来,我一直在使用不同的JavaScript,ASP控件和常规控件的组合来调试Ajax调用。我已经对发生的事情有了一些了解,但是使用ASP控件仍然隐藏了太多的机器,我希望有更深入的了解。有了这个目标,谁能告诉我为什么下面的设置不起作用?使用.aspx页面作为Ajax事件处理程序?
我有一个文件 “Testy.aspx” 有以下几点:
<asp:Content>
<script type="text/javascript">
// a standard home-grown Ajax javascript method
function ajaxfunction() {
var ajaxObj = getAjaxObj(); // does the usual browser-detection
if (ajaxObj) {
ajaxObj.open("GET", "Testy.aspx", true);
ajaxObj.setRequestHeader("IsAjaxRequest", "true");
ajaxObj.send();
ajaxObj.onreadystatechange = function() {
if (ajaxObj.readyState == 4) {
document.getElementById("testytext").appendChild(document.createTextNode(ajaxObj.responseText));
}
}
}
}
</script>
... other unrelated html, ASP controls, etc...
<input id="testybutton" type="button" value="baroo" onclick="ajaxfunction()" />
<div id="testytext"></div>
</asp:Content>
同时,我有一个代码隐藏功能 “Testy.aspx.vb” 有以下几点:
Partial Public Class Testy
Inherits System.Web.UI.Page
Implements System.Web.IHttpHandler
...code for an ordinary (non-Ajax) request is in the middle here...
' Now I have code for Ajax requests
Overrides Sub ProcessRequest(ByVal context As HttpContext)
If context.Request.Headers("IsAjaxRequest") = "true" Then
context.Response.ContentType = "text/plain"
context.Response.Write("Hello World!")
Else
MyBase.ProcessRequest(context)
End If
End Sub
Overloads ReadOnly Property IsReusable() As Boolean
Get
Return False
End Get
End Property
End Class
所以,我希望使我的.aspx文件兼作常规页面请求处理程序和Ajax请求处理程序。但是,当我点击按钮(“baroo”)生成Ajax请求时,写回到“testytext”div的结果就是整个页面的原始html,就像在正常的请求条件下一样。显然,我试图通过使代码隐藏实现IHttpHandler并提供“Overrides Sub ProcessRequest”方法来覆盖页面请求不起作用。服务器仍然将Ajax请求视为正常请求,事实上,我自己的“ProcessRequest”方法甚至不会被调用。
是否有可能建立一个像这样的页面/处理程序?我如何拦截来自客户端的传入请求并作出相应的响应?这就是Ajax的工作原理,对吧?所以它一定是可能的。
同样,我故意这样做是为了避免使用诸如UpdatePanels之类的“魔术”ASP控件,因此请不要通知其使用。
@Noel,我倾向于同意下面的Chris - 您可以创建一个不同的ashx(或根据您的需要asmx)。至于为什么上述不起作用,我的猜测是你的请求头没有到达服务器 - 尝试在VS中的ProcessRequest中放置一个断点并检查它。 – VinayC 2011-04-14 04:02:51