我遇到了ajax get请求的问题。我搜索过但是我找不到任何与ajax get错误相关的内容但是有关POST请求的内容。我的问题是,当我通过ajax
GET请求在asp.net中调用webmethod时,响应包含整个页面而不是必需的响应。我还在visual studio中使用断点来查看函数是否被触发。它不是。当我通过ajax
使用POST请求时,它工作正常。
我的javascript
代码:
$('#count').click(function () {
alert("button clicked");
$.ajax({
url: "WebForm1.aspx/Count",
method: "GET",
dataType: "text",
success: function (response) {
alert(response);
}
});
});
Asp.Net
代码
public static int Count()
{
int length = messages.Count;
return length;
}
答案 0 :(得分:1)
如果您想使用HttpGet,则需要[ScriptMethod(UseHttpGet = true)]
。此外,代码缺少少量Ajax设置 - type: "GET"
(而不是method
)和contentType: "application/json"
。
<button id="count" type="button">Count</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$('#count').click(function () {
alert("button clicked");
$.ajax({
url: '<%= ResolveUrl("~/WebForm1.aspx/Count") %>',
type: "GET",
contentType: "application/json",
success: function (response) {
console.log(response.d);
}
});
});
</script>
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public static int Count()
{
return 123;
}
仅供参考: 我们通常不会设置dataType: "text"
;相反,我们只接受它作为Json,并将返回数据检索为response.d
。
答案 1 :(得分:0)
在asp.net中代替return count;
使用return Json(new {length= message.count});
在Js中alert(response)
使用alert(response.length)
。
希望这会有所帮助。
答案 2 :(得分:0)
您尝试在页面类中访问一个方法,但在asp.net webform中,您可以使用通用处理程序或web方法进行ajax调用。
处理程序示例
public class Handler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
//do something
}
public bool IsReusable {
get {
return false;
}
}
}
和ajax
url: "Handler url"