jQuery入门(9):Ajax(调用页面方法和WebService)

调用页面方法和webservice

注:

web.config中要指定允许调用web服务。

必须为Post方式来调用。

WEB服务返回的为XML串,所以客户端要转换为JSON再处理。

        [WebMethod]

        public static string AjaxServiceTest(string str)

        {

            return string.Format("Hello,{0}", str);

        } 

    [System.Web.Script.Services.ScriptService]

    public class TestWebService : System.Web.Services.WebService

    {

        [WebMethod]

        public string HelloWorld(string s)

        {

            return "Hello World" + s ;

        }

    } 

        function WebServiceMethod() {

            $.ajax({

                type: "POST",

                contentType: "application/json;utf-8",

                url: "TestWebService.asmx/HelloWorld",

                data: "{s:""" + $("#inputName").val() + """}", //传webservice方法的参数,s是方法的参数,必须一致                                         

                success: function(data) {

                    //将返回字符串转换为json对象

                    var json = null;

                    try {

                        json = eval('(' + data + ')');

                    } catch (e) {

                        alert("返回字符串不是json格式!");

                        return;

                    }

                    alert(json.d);

                }

            });

        }

        function PageAjaxServiceTest() {

            $.ajax({

                type: "POST",

                contentType: "application/json;utf-8",

                url: "PageService.aspx/AjaxServiceTest",

                data: "{str:""" + $("#inputName").val() + """}", //传到.cs静态方法的参数,str是方法的参数,必须一致                                    

                success: function(data) {

                    //将返回字符串转换为json对象

                    var json = null;

                    try {

                        json = eval('(' + data + ')');

                    } catch (e) {

                        alert("返回字符串不是json格式!");

                        return;

                    }

                    alert(json.d);

                }

            });

        }

    </script>

    <div>

    <input id="inputName" type="text" value="" />

    <a href="#" onclick="WebServiceMethod();">调用web服务</a><br /><br />

    <a href="#" onclick="PageAjaxServiceTest();">调用页面静态方法</a><br /><br />

    </div> 

        $.post("PagingService.asmx/GetLoginHtml", { s: "fda" },

         function(data) {

             $("#ajaxlogin").html(data);

             alert(data);

         }, "html");

 

posted @ 2008-11-19 10:04  Astar  阅读(...)  评论(...编辑  收藏