0

我不想用 jquery $.ajax 调用 asp.net 服务器端代码。所以我写了一个纯 javascript ajax 文件。但是当我调用 webmethod 时,这不起作用。任何人都可以帮我解决这个问题吗?非常感谢你 。

ajax.js:

var ajax = {
    _params: null,
_callback: null,
 _xhr: null,
_createXHR: function () {
if (window.ActiveXObject) {
 _xhr = new ActiveXObject("Microsoft.XMLHTTP");     //IE
}
    else if (window.XMLHttpRequest) {
        _xhr = new XMLHttpRequest();      //FireFox,Chrome et.
    }
},

_ajaxcallback: function () {
    if (_xhr.readyState == 4) {
        if (_xhr.status == 200) {
            _callback.call(this, _xhr.responseText)
        }
    }
},

_changeParams: function () {
    var args = arguments[0];
    var s = "";
    for (var i in args) {
        s += "&" + i + "=" + args[i];
    }
    _params = s;
},

get: function (url, params, callback) {
    _callback = callback;
    ajax._createXHR();
    ajax._changeParams(params);
    if (null != _xhr) {
        _xhr.open('get', url + '?' + _params, true);
        _xhr.onreadystatechange = ajax._ajaxcallback;
        _xhr.send();
    }
},

post: function (url, params, callback) {
    _callback = callback;
    ajax._createXHR();
    ajax._changeParams(params);
    if (null != _xhr) {
        _xhr.open('post', url, true);
        _xhr.onreadystatechange = ajax._ajaxcallback;
        _xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        _xhr.send(_params);
    }
}
}

WebForm1.aspx

<head runat="server">
<title></title>
<script src="ajax.js" type="text/javascript"></script>
<script type="text/javascript">
    function ajaxtest() {
        var uid = document.getElementById("txtuid").value;
        var pwd = document.getElementById("txtpwd").value;
        ajax.post("WebForm1.aspx/GetModel", "{ 'uid':" + uid + ", 'pwd':" + pwd + " }", function (data) {
            alert(data);
        });
    }
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<input type="text" id="txtuid" value="eeee" />
<input type="text" value="222" id="txtpwd" onblur="ajaxtest()"/>

WebForm1.cs:

     [WebMethod]
    public static string GetModel(string uid,string pwd)
    {

     return "1";
    }
4

2 回答 2

3

在您的标记中,您需要将ScriptManagerwithEnablePageMethods设置为 true。这样做将确保您可以调用已标记的方法[WebMethod]

在你的 JavaScript 中,你可以像这样调用你的方法:PageMethods.GetModel("userName", "password", OnSuccessMethod, OnFailureMethod);- 如果你这样做,你将不需要任何ActiveXObject/XmlHttpRequest东西,这让事情变得更简单。

于 2012-10-09T02:17:09.720 回答
0

使用 Michael Schwarz 的 AJAX.PRO --> http://www.ajaxpro.info/

于 2012-10-09T15:03:56.013 回答