如果標記C#函數作爲[的WebMethod]或使ASP.NET web服務的一部分它是用jQuery相對容易。這兩種技術都可以很容易地將響應自動轉換爲ASP.NET的JSON對象,這使得客戶端的處理更加容易(恕我直言)。
下面的例子是如果頁面有一個名爲GetData
的WebMethod
,但是如果你創建一個服務,那麼改變這個URL是微不足道的。
$.ajax({ url: "somepage.aspx/GetData",
method: "POST", // post is safer, but could also be GET
data: {}, // any data (as a JSON object) you want to pass to the method
success: function() { alert('We did it!'); }
});
在服務器上:
[WebMethod]
public static object GetData() {
// query the data...
// return as an anonymous object, which ASP.NET converts to JSON
return new { result = ... };
}
如果webmethod在頁面內部,它需要是靜態的,但如果它在web服務中不需要使其靜態。 – 2010-03-01 15:02:31
偉大的提示!非常感謝 :] – cc0 2010-03-01 15:23:14