【发布时间】:2012-02-03 01:18:46
【问题描述】:
我是 ASP.NET 和 Ajax 的新手。我正在尝试实现一个示例应用程序,它可以在没有回发的情况下更新 Web 表单。单击时,我的应用程序使用 XMLHttpRequestModule 向其服务器发送请求,并显示通过警报窗口接收到的数据。
我认为问题可能是 default.aspx.cs 页面没有将 httpRequest.responseText 提供给其网络表单。
参见。 XMLHttpRequestModule 中的 sendRequest 方法用于检查与浏览器的兼容性,并使用指定的参数和方法发送请求。
非常感谢任何帮助。
默认.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="XMLHttpRuquestModule.htm"></script>
<script type="text/javascript">
function helloToServer() {
var params = "name=" + encodeURIComponent(document.form.name.value);
sendRequest("Default.aspx", params, helloFromServer, "POST");
}
function helloFromServer() {
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
alert("Response: " + httpRequest.responseText);
}
}
}
</script>
</head>
<body>
<form name ="form" runat="server">
<input type="text" name="name" />
<input type="button" value="enter" onclick="helloToServer()" />
</form>
</body>
</html>
默认.aspx.cs
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
String name = Request["name"];
Response.Write(name);
return;
}
}
XMLHttpRequestModule
<head>
<title></title>
<script type="text/javascript">
var httpRequest = null;
function getXMLHttpRequest() {
if (window.ActiveXObject) {
try {
return new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
return new ActiveXObject("Microsoft.XMLHTTP");
} catch (e1) {
return null;
}
}
} else if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else {
return null;
}
}
function sendRequest(url, params, callback, method) {
httpRequest = getXMLHttpRequest();
var httpMethod = method ? method : 'GET';
if (httpMethod != 'GET' && httpMethod != 'POST') {
httpMethod = 'GET';
}
var httpParams = (params == null || params == '') ? null : params;
var httpUrl = url;
if (httpMethod == 'GET' && httpParams != null) {
httpUrl = httpUrl + "?" + httpParams;
}
httpRequest.open(httpMethod, httpUrl, true);
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.onreadystatechange = callback;
httpRequest.send(httpMethod == 'POST' ? httpParams : null);
}
</script>
</head>
【问题讨论】:
-
什么是'cf。 sendRequest' 以及它在您的代码中的什么位置?
-
sendRequest 方法位于我在此代码中提到的 XMLHttpRequestModule.htm 中。 sendRequest 方法有四个参数(url、params、callback、method)
-
要我上传 XMLHttpRequestModule.htm 吗?
-
是的。请编辑您的问题和所有相关代码。
标签: c# asp.net ajax xmlhttprequest