从javascript调用webmethod时,ASP.NET 500内部服务器出错

Mun*_* A. 7 javascript c# asp.net ajax

我试图webmethod使用AJAX 调用功能,但无法获得适当的结果.我搜索了我的问题并找到了许多解决方案,但那些对我没用.请指导我做错了什么.帮助将不胜感激.

干杯

代码片段

 function checkUserNameExists() {

//initialization
var pagePath = window.location.pathname + "/getUsername";
var value = document.getElementById('control_userName').value;
var dataString = "{ 'value':'" + value + "' }";
$.ajax({
    type: "GET",
    url: pagePath,
    data: dataString,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    error:
            function (XMLHttpRequest, textStatus, errorThrown) {

            },
    success:
            function (result) {
                var flag = true;
                if (result != null) {
                    flag = result.d;
                    if (flag == "True") {
                        alert('okay fine you are good');
                    }
                    else {
                        alert('try again');
                    }
                }
            }
});
 }
Run Code Online (Sandbox Code Playgroud)

代码文件后面的方法

    [WebMethod]
    [ScriptMethod(UseHttpGet = true)]
    public string getUsername(string value)
    {
        return "True";
    }
Run Code Online (Sandbox Code Playgroud)

例外

 ExceptionType: "System.InvalidOperationException"
  Message: "An attempt was made to call the method 'getUsername' using a        POST request, which is not allowed."
Run Code Online (Sandbox Code Playgroud)

Sha*_*arB 7

首先,如果web方法在页面类中,而不在Web服务类中,则它应该是静态的。

其次,传输的数据实际上不是字符串,而是对象,因此将其更改为:

var dataString = { 'value':  value  };
Run Code Online (Sandbox Code Playgroud)

第三件事,“类型”用于旧版本的jquery,您应该将ajax调用更改为:

method: "GET",
url: pagePath,
data: dataString,
contentType: "application/json; charset=utf-8",
dataType: "json",...
Run Code Online (Sandbox Code Playgroud)

或更改服务器端的功能以获取帖子调用,方法是删除

UseHttpGet = true
Run Code Online (Sandbox Code Playgroud)