Function 需為靜態,且標示為 [WebMethod]
using System.Web.Services; //[WebMethod]
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string getHello(string str)
{
return str;
}
Client 端 (AjaxTestPage1.aspx) 引用 jQuery (使用 Google CDN)
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
用來呼叫 Server 端的函數 (使用 ajax)。
<script>
function CallServerFunction(StrPriUrl, ObjPriData, CallBackFunction) {
$.ajax({
type: "post",
url: StrPriUrl,
contentType: "application/json; charset=utf-8",
data: ObjPriData,
dataType: "json", //"text"
async: true, //true (非同步執行) false(同步執行)
success: function (result) {
if (CallBackFunction != null && typeof CallBackFunction != 'undefined') {
CallBackFunction(result);
}
},
error: function (result) {
alert('error occured');
alert(result.responseText);
},
});
}
</script>
呼叫方法:CallServerFunction("[網址路徑] / [Server端函數名稱]", [Server端Function的接收參數], [接收回傳值的函數])
<script>
function test() {
CallServerFunction("AjaxTestPage1.aspx/getHello", "{'str':'123'}", function (myresult) {
alert(JSON.stringify(myresult));
alert(myresult.d);
});
}
</script>
呼叫的方式
沒有留言:
張貼留言