我正在尝试使用 AJAX 调用 webmethod
功能,但无法获得适当的结果。我用谷歌搜索了我的问题并找到了很多解决方案,但这些对我没有用。请指导我做错了什么。帮助将不胜感激。
干杯
代码片段
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');
}
}
}
});
}
Behind Code 文件中的方法
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string getUsername(string value)
{
return "True";
}
例外
ExceptionType: "System.InvalidOperationException"
Message: "An attempt was made to call the method 'getUsername' using a POST request, which is not allowed."
原文由 M A. 发布,翻译遵循 CC BY-SA 4.0 许可协议
首先,如果 web 方法在页面类中,而不是在 Web 服务类中,那么它应该是静态的。
第二,传输的数据并不是真正的字符串,而是一个对象,因此将其更改为:
第三件事,“类型”适用于旧版本的 jquery,您应该将 ajax 调用更改为:
或者更改服务器端的功能以通过删除