ASP.NET前台AJAX方法调用后台的方法写法

时间:2023-03-08 23:25:55
ASP.NET前台AJAX方法调用后台的方法写法

前台:

<input id="AjaxDemo" type="button" onclick="get()" value="开始" />
<script type="text/javascript">
//$().ready(
// function () {
// $("#AjaxDemo").click(function () {
// $.ajax({
// type: "POST",
// url: "AJAXTest.aspx/ABC",
// data: "{'ABC':'test'}",
// dataType: "json",
// contentType: "application/json; charset=utf-8",
// success: function (msg) { alert(msg.d); }
// })
// })
// }
// )
$(function () {
$("#AjaxDemo").click(function () {
$.ajax({
type: "POST",
url: "AJAXTest.aspx/GetAddress",
//data: "{'ABC':'test'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (msg) { alert(msg.d); }
})
})
})
</script>

后台:

 [WebMethod]
//[AjaxMethod]
public static string GetAddress()
{
string Address = "hello word";
//do somthing to get the address here
return Address;
} [WebMethod]
public static string ABC(string ABC)
{
return ABC;
}

注意要素:后台方法必须加入webmethod标记,并且为静态方法,而且据我试验了一下貌似GET方式是不可以的,如果有大神可以使用get方式完成这个功能还请指教,而且返回的数据最好是JSON格式的,msg的属性必须是d,具体是为什么暂时不知道,即,msg.d,d是必须的