如何使用jQueryAJAX调用ASP.Net字符串函数



我有一个字符串函数ASP.Net Webform。我想用AJAX调用这个函数。该函数从带有月份索引的数据库中返回一个字符串值

protected string BringDatas(int month)
{
Counts counts_ = new Counts();
return counts_.GetMonths(month);
}
var dataValue = { "month": 1 };
$.ajax({
type: "POST",
url: "Homepage.aspx/BringDatas",
data: dataValue,
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "nnStatus: " + textStatus + "nnError: " + errorThrown);
},
complete: function (jqXHR, status) {
alert("complete: " + status + "nnResponse: " + jqXHR.responseText);
}
});

试试看:

代码隐藏:

[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string BringDatas(int month)
{
Counts counts_ = new Counts();
return counts_.GetMonths(month);
}

ajax调用

$.ajax({
type: 'GET',
url: 'Homepage.aspx/BringDatas',
data: '{"month": 1}',
contentType: "application/json; charset=utf-8",
dataType: 'json',
async: false,
success: function (response) {
alert("Response: " + response.d);
},
error: function (response) {
}
});

这是javascript端的

<script type="text/javascript">
$(document).ready(
function () {
$("#Gonder").click(
function () {

$.ajax
({
type: "POST",
url: "Homepage.aspx/OrnekPost",
data: "{'parametre':'1234'}",
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function (output) {
alert("Response: "+ output);
}, error: function () {
alert("hata var");
}
});
});
})
</script>

Codebehind.cs代码

[ScriptMethod]
[WebMethod(EnableSession = true)]
public static string OrnekPost(string parametre)
{
return parametre + " değeriyle post işlemi gerçekleştirildi.";
}

最新更新