Call web service via jQuery in asp.net
step 1. Add Web service, and you must add a [System.Web.Script.Services.ScriptService] to the service class
(in webservice.asmx.cs file)
1: /// <summary>
2: /// Summary description for WebService1
3: /// </summary>
4: [WebService(Namespace = "http://tempuri.org/")]
5: [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
6: [System.ComponentModel.ToolboxItem(false)]
7: // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
8: [System.Web.Script.Services.ScriptService]
9: public class WebService1 : System.Web.Services.WebService
10: {
11: [WebMethod]
12: public string DeleteProduct(string id)
13: {
14: Thread.Sleep(800);
15: return "Hello World22: " + id;
16: }
17: }
step 2. call webservice in aspx via jQuery
(in head of the page)
1: <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
2: <script type="text/javascript">
3: $(function () {
4: $('a').click(function () {
5: deleteProduct(111);
6: }); // end of $('a').click(function () {
7:
8: }); // end of $(function () {
9:
10:
11:
12: function deleteProduct(id) {
13: $.ajax({
14: type: "POST",
15: url: "WebService1.asmx/DeleteProduct",
16: data: "{id: '" + id.toString() + "'}",
17: contentType: "application/json; charset=utf-8",
18: dataType: "json",
19: success: function (msg) {
20: AjaxSucceeded(msg);
21: },
22: error: AjaxFailed
23: });
24: }
25: function AjaxSucceeded(result) {
26: alert(result.d);
27: }
28: function AjaxFailed(result) {
29: alert(result.status + ' - ' + result.statusText);
30: }
31: </script>
