使用 XMLHttpRequest 的 ASP.NET AJAX 简单应用程序

发布于 2024-12-24 20:14:48 字数 2882 浏览 2 评论 0原文

我是 ASP.NET 和 Ajax 的新手。我正在尝试实现一个无需回发即可更新 Web 表单的示例应用程序。单击后,我的应用程序使用 XMLHttpRequestModule 向其服务器发送请求,并显示通过警报窗口接收到的数据。

我认为问题可能是 default.aspx.cs 页面没有将 httpRequest.responseText 提供给其网络表单。

参见sendRequest 方法位于 XMLHttpRequestModule 中,用于检查与浏览器的兼容性并使用指定的参数和方法发送请求。

非常感谢任何帮助。

Default.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>

Default.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>

I am a newbie to ASP.NET and Ajax. I am trying to implement a sample application that updates web form without Postback. On click, my application sends request to its server using XMLHttpRequestModule and shows the data received through an alert window.

I think the problem might be that default.aspx.cs page is not giving the httpRequest.responseText to its webform.

cf. sendRequest method is in XMLHttpRequestModule to check the compatibility with browsers and send a request using the specified parameters and methods.

Any help is much appreciated.

Default.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>

Default.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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

月下伊人醉 2024-12-31 20:14:48

在您的问题中,您提到了通过脚本标记包含的 XMLHttpRequestModule< /代码>。 XMLHttpRuquestModule.htm 有拼写错误(“Ruquest”而不是“Request”),也许这导致了您的错误。

另请注意,只有在该文件中有 JavaScript 并且没有实际的 html 时,在脚本中包含 htm 文件才会起作用。

编辑:

这是参考我们在评论部分的交流。

我已经设法获得一个 ASP.NET 服务器,针对与您的完全一样的 ASPX 页面运行 Ajax 代码,一切仍然正常。警报框仍然弹出正确的响应。

不同之处在于,正如最初建议的那样,我已将您的 XMLHttpRuquestModule.htm 重命名为 XMLHttpRuquestModule.js 并删除了其中的所有标记。

我在这里复制所有代码,尝试准确粘贴然后运行它:

HTML 文件(testXhr.htm):

<html>
    <head>
    <title></title>
    <script type="text/javascript" src="XMLHttpRequestModule.js"></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>

JavaScript 文件(XMLHttpRequestModule.js):

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);
}

In your question you mentioned a XMLHttpRequestModule that you included through the script tag: <script type="text/javascript" src="XMLHttpRuquestModule.htm"></script>. XMLHttpRuquestModule.htm has spelling error in it ('Ruquest' instead of 'Request'), maybe that is causing your error.

Also note that including an htm file in the script will only work if there is JavaScript in that file and no actual html.

EDIT:

This is with reference to our exchange in the comments section.

I have managed to get hold of a ASP.NET server, ran the Ajax code against an ASPX page exactly like yours and everything is still okay. The alert box is still popping the correct response.

The difference is that, as originally suggested, I have renamed your XMLHttpRuquestModule.htm to XMLHttpRuquestModule.js and removed all markup from within it.

I am copying all the code here, try pasting it exactly and then running it:

HTML File(testXhr.htm):

<html>
    <head>
    <title></title>
    <script type="text/javascript" src="XMLHttpRequestModule.js"></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>

JavaScript File(XMLHttpRequestModule.js):

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);
}
太阳公公是暖光 2024-12-31 20:14:48

直接使用 XMLHttpRequest 有很多问题。其中之一是跨浏览器兼容性。您应该尝试使用 jQuery 来创建 ajax 调用。您可以创建 WebMethods 是从 javascript 调用的 ASP.Net 页面。看看它们

将 jQuery 用于 AJAX 和 ASP.NET Webforms

http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

编辑:

如果你想使用纯 Javascript,请尝试

http://lamahashim.blogspot.com/2010/03/accessing-aspnet-webmethod-from.html

http://msdn.microsoft.com/en-us/library/ms535874%28v=vs.85%29.aspx

There are many issue using XMLHttpRequest directly. one of them is cross browser compatibility.. you should try using jQuery to create ajax calls. and you can create WebMethods is ASP.Net page to be called from javascript. have a look at them

Using jQuery for AJAX with ASP.NET Webforms

http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/

EDIT:

In you want to use pure Javascript try

http://lamahashim.blogspot.com/2010/03/accessing-aspnet-webmethod-from.html

http://msdn.microsoft.com/en-us/library/ms535874%28v=vs.85%29.aspx

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文