To call the Web Service from client-side, I have used JQuery’s
ajax
method. In JQuery’s ajax
method, you need to set the request type to post, as an AJAX Web Service (by default) doesn’t allow methods to be called via the HTTP GET method (how to enable HTTP GET in a Web Service?). For your information, ASP.NET AJAX controls like UpdatePanel
uses HTTP POST when sending asynchronous requests. Below is the JQuery method that will call the Web Service method.$.ajax({
type: "POST",
data: "{'prefix':''}",
url: "/YourWebService.asmx/MethodName",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: functionToCallWhenSucceed,
failure: funcitonToCallWhenFailed
});
See the following Example...
Here I'm using the Webservice earlier created in this blog...
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head id="Head1" runat="server"> <title></title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function () { $("#btnsubmit").bind("click", function () { var name = $("#txtname").val(); $("#query_results").empty(); $("#query_results").append('<table id="ResultsTable" class="AccountsTable"><tr><th>AccId</th><th>AccName</th></tr>'); $.ajax({ type: "POST", url: "WebService.asmx/GetAccountdetailsByName", data: "{'name':'" + name + "'}", contentType: "application/json; charset=utf-8", dataType: "json", success: sucesscallback, error: FailureCallBack }); }) }); function sucesscallback(msg) { var c = eval(msg.d); for (var i in c) { $("#ResultsTable tr:last").after("<tr><td>" + c[i][0] + "</td><td>" + c[i][1] + "</td></tr>"); } } function FailureCallBack(data) { alert("Failure"); } </script> </head> <body> <form id="form1" runat="server"> <div> <input type ="text" ID ="txtname" runat ="server" /> <input type="button" ID ="btnsubmit" value ="submit" runat ="server" /> </div> <div id="query_results"> </div> </form> </body> </html> |
No comments:
Post a Comment