从javascript调用webmethod时ASP.NET 500内部服务器错误 [英] ASP.NET 500 Internal Server Error while calling webmethod from javascript
问题描述
我正在尝试使用AJAX调用webmethod
功能,但无法获得适当的结果.我已经搜索了我的问题,找到了许多解决方案,但是这些解决方案对我没有用.请指导我我在做什么错.帮助将不胜感激.
I'm trying to call the webmethod
fucntionality using AJAX but unable to get the appropriate results. I have googled my problem and found many solution but those didn't worked for me. Please guide me what I'm doing wrong. Help will be appreciated.
欢呼
代码段
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');
}
}
}
});
}
隐藏代码文件中的方法
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string getUsername(string value)
{
return "True";
}
EXCEPTION
ExceptionType: "System.InvalidOperationException"
Message: "An attempt was made to call the method 'getUsername' using a POST request, which is not allowed."
推荐答案
首先,如果web方法在页面类中,而不在Webservice类中,则它应该是静态的.
First, it the webmethod is in the page class, and not in a Webservice class, then it should be static.
第二,传输的数据实际上不是字符串,而是对象,因此将其更改为:
Second, the data transfered is not really a string, but an object, so change it to:
var dataString = { 'value': value };
第三件事,类型"用于旧版本的jquery,您应该将ajax调用更改为:
Third thing, "type" is for older versions of jquery, you should either change your ajax call to:
method: "GET",
url: pagePath,
data: dataString,
contentType: "application/json; charset=utf-8",
dataType: "json",...
或通过删除
UseHttpGet = true
这篇关于从javascript调用webmethod时ASP.NET 500内部服务器错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!