zoukankan      html  css  js  c++  java
  • jQuery Ajax 调用Aspx.Net WebService

    我在这里将jQuery Ajax 调用Aspx.Net WebService 的几个常用的方法做了一个整理,提供给正在找这方面内容的博友,希望能给学习jQuery的朋友一点帮助,可以直接复制代码运行。

    ws.aspx 代码

    <!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 src="jquery.js" type="text/javascript"></script>

        <style type="text/css">
            .hover
            {
                cursor: pointer; /*小手*/
                background: #ffc; /*背景*/
            }
            .button
            {
                150px;
                float: left;
                text-align: center;
                margin: 10px;
                padding: 10px;
                border: 1px solid #888;
            }
            #dictionary
            {
                text-align: center;
                font-size: 18px;
                clear: both;
                border-top: 3px solid #888;
            }
            #loading
            {
                border: 1px #000 solid;
                background-color: #eee;
                padding: 20px;
                margin: 100px 0 0 200px;
                position: absolute;
                display: none;
            }
            #switcher
            {
            }
        </style>

        <script type="text/javascript">

            //无参数调用
            $(document).ready(function() {
                $('#btn1').click(function() {
                    $.ajax({
                        type: "POST",   //访问WebService使用Post方式请求
                        contentType: "application/json", //WebService 会返回Json类型
                        url: "WebService1.asmx/HelloWorld", //调用WebService的地址和方法名称组合 ---- WsURL/方法名
                        data: "{}",         //这里是要传递的参数,格式为 data: "{paraName:paraValue}",下面将会看到      
                        dataType: 'json',
                        success: function(result) {     //回调函数,result,返回值
                            $('#dictionary').append(result.d);
                        }
                    });
                });
            });

            //有参数调用
            $(document).ready(function() {
                $("#btn2").click(function() {
                    $.ajax({
                        type: "POST",
                        contentType: "application/json",
                        url: "WebService1.asmx/GetWish",
                        data: "{value1:'心想事成',value2:'万事如意',value3:'牛牛牛',value4:2009}",
                        dataType: 'json',
                        success: function(result) {
                            $('#dictionary').append(result.d);
                        }
                    });
                });
            });
           
           
            //返回集合(引用自网络,很说明问题)
            $(document).ready(function() {
                $("#btn3").click(function() {
                    $.ajax({
                        type: "POST",
                        contentType: "application/json",
                        url: "WebService1.asmx/GetArray",
                        data: "{i:10}",
                        dataType: 'json',
                        success: function(result) {
                            $(result.d).each(function() {
                                //alert(this);
                                $('#dictionary').append(this.toString() + " ");
                                //alert(result.d.join(" | "));
                            });
                        }
                    });
                });
            });

            //返回复合类型
            $(document).ready(function() {
                $('#btn4').click(function() {
                    $.ajax({
                        type: "POST",
                        contentType: "application/json",
                        url: "WebService1.asmx/GetClass",
                        data: "{}",
                        dataType: 'json',
                        success: function(result) {
                            $(result.d).each(function() {
                                //alert(this);
                                $('#dictionary').append(this['ID'] + " " + this['Value']);
                                //alert(result.d.join(" | "));
                            });

                        }
                    });
                });
            });==============
    var aArray = [“sdf”,”dasd”,”dsa”]; //数组$.each(aArray,function(iNum,value){       document.write(“序号:”+iNum+” 值:”+value);});var oObj = {one:1,two:2,three:3};$.each(aArray,function(property,value){       document.write(“属性:”+ property +” 值:”+value);});==============================================
            //返回DataSet(XML)
            $(document).ready(function() {
                $('#btn5').click(function() {
                    $.ajax({
                        type: "POST",
                        url: "WebService1.asmx/GetDataSet",
                        data: "{}",
                        dataType: 'xml', //返回的类型为XML ,和前面的Json,不一样了
                        success: function(result) {
                        //演示一下捕获
                            try {  
                                $(result).find("Table1").each(function() {
                                    $('#dictionary').append($(this).find("ID").text() + " " + $(this).find("Value").text());
                                });
                            }
                            catch (e) {
                                alert(e);
                                return;
                            }
                        },
                        error: function(result, status) { //如果没有上面的捕获出错会执行这里的回调函数
                            if (status == 'error') {
                                alert(status);
                            }
                        }
                    });
                });
            });

            //Ajax 为用户提供反馈,利用ajaxStart和ajaxStop 方法,演示ajax跟踪相关事件的回调,他们两个方法可以添加给jQuery对象在Ajax前后回调
            //但对与Ajax的监控,本身是全局性的
            $(document).ready(function() {
                $('#loading').ajaxStart(function() {
                    $(this).show();
                }).ajaxStop(function() {
                    $(this).hide();
                });
            });

            // 鼠标移入移出效果,多个元素的时候,可以使用“,”隔开
            $(document).ready(function() {
                $('div.button').hover(function() {
                    $(this).addClass('hover');
                }, function() {
                    $(this).removeClass('hover');
                });
            });
           
           
        </script>

    </head>
    <body>
        <form id="form1" runat="server">
        <div id="switcher">
            <h2>
                jQuery 的WebServices 调用</h2>
            <div class="button" id="btn1">
                HelloWorld</div>
            <div class="button" id="btn2">
                传入参数</div>
            <div class="button" id="btn3">
                返回集合</div>
            <div class="button" id="btn4">
                返回复合类型</div>
            <div class="button" id="btn5">
                返回DataSet(XML)</div>
        </div>
        <div id="loading">
            服务器处理中,请稍后。
        </div>
        <div id="dictionary">
        </div>
        </form>
    </body>
    </html>
    WebService1.asmx.cs

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    using System.Data;

    namespace jQuery.Learning
    {
        /// <summary>
        /// WebService1 的摘要说明
        /// </summary>
        [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [System.ComponentModel.ToolboxItem(false)]
        // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
        [System.Web.Script.Services.ScriptService]
        public class WebService1 : System.Web.Services.WebService
        {
            /// <summary>
            /// 无参数
            /// </summary>
            /// <returns></returns>
            [WebMethod]
            public string HelloWorld()
            {
                return "Hello World ";
            }

            /// <summary>
            /// 带参数
            /// </summary>
            /// <param name="value1"></param>
            /// <param name="value2"></param>
            /// <param name="value3"></param>
            /// <param name="value4"></param>
            /// <returns></returns>
            [WebMethod]
            public string GetWish(string value1, string value2, string value3, int value4)
            {
                return string.Format("祝您在{3}年里 {0}、{1}、{2}", value1, value2, value3, value4);
            }

            /// <summary>
            /// 返回集合
            /// </summary>
            /// <param name="i"></param>
            /// <returns></returns>
            [WebMethod]
            public List<int> GetArray(int i)
            {
                List<int> list = new List<int>();

                while (i >= 0)
                {
                    list.Add(i--);
                }

                return list;
            }

            /// <summary>
            /// 返回一个复合类型
            /// </summary>
            /// <returns></returns>
            [WebMethod]
            public Class1 GetClass()
            {
                return new Class1 { ID = "1", Value = "牛年大吉" };
            }

            /// <summary>
            /// 返回XML
            /// </summary>
            /// <returns></returns>
            [WebMethod]
            public DataSet GetDataSet()
            {
                DataSet ds = new DataSet();
                DataTable dt = new DataTable();
                dt.Columns.Add("ID", Type.GetType("System.String"));
                dt.Columns.Add("Value", Type.GetType("System.String"));
                DataRow dr = dt.NewRow();
                dr["ID"] = "1";
                dr["Value"] = "新年快乐";
                dt.Rows.Add(dr);
                dr = dt.NewRow();
                dr["ID"] = "2";
                dr["Value"] = "万事如意";
                dt.Rows.Add(dr);
                ds.Tables.Add(dt);
                return ds;
            }

        }
        //自定义的类,只有两个属性
        public class Class1
        {
            public string ID { get; set; }
            public string Value { get; set; }
        }
    }

    本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/shuilv2000/archive/2009/11/24/4863977.aspx

    JQuery 中的Ajax调用WebServices 的总结 收藏
    使用JQuery中javascript:;" onClick="javascript:tagshow(event, 'ajax');" target="_self">ajax方法访问web服务。

    1.ajax方法需要填写:
     

    JScript. code
    $.ajax({type:"POST",//注明 返回JsoncontentType:"application/json;utf-8",//CollegeDepartWebServices.asmx web服务名 /GetCollegeDepart 方法名http://www.cnblogs.com/tangself/admin/%22CollegeDepartWebServices.asmx/GetCollegeDepart%22,//strDepartId 参数名称 collegeId 参数值data:"{strDepartId:"+collegeId+"}",dataType:"json",success:function(result){varjson=nulltry{if(result){//因为返回的是ArrayList 所以循环取出其中的值$.each(result,function(i, n){//ddlDepart 为下来菜单。循环的向下拉菜单中添加新的选项ddlDepart.options[ddlDepart.length]=newOption(n.CollegeDepartTitle,n.CollegeDepartId);});}}catch(e){alert("错误>>"+e.message);return;}},error:function(data){alert(data.status+">>>"+data.statusText);}});

    ----
    CollegeDepartWebServices.asmx.cs web服务类

    C# code
    [WebService(Namespace="http://tempuri.org/%22)][WebServiceBinding(ConformsTo=WsiProfiles.BasicProfile1_1)][ScriptService]publicclassCollegeDepartWebServices : System.Web.Services.WebService{publicCollegeDepartWebServices(){//如果使用设计的组件,请取消注释以下行//InitializeComponent();}[WebMethod][System.Xml.Serialization.XmlInclude(typeof(CollegeDepartInfo))]publicArrayList  GetCollegeDepart(stringstrDepartId){CollegeDepartBL.FlushCollegeDepartCache();if(string.IsNullOrEmpty(strDepartId))returnnull;ArrayList myList=CollegeDepartBL.GetCollegeDepartListByCollegeID(int.Parse(strDepartId));returnmyList;}}

    说明:
    ArrayList 中 存为对象CollegeDepartInfo
    其属性为:stirng CollegeDepartTitle 和 int CollegeDepartId
    在javascript中
    ddlDepart.options[ddlDepart.length]=new Option(n.CollegeDepartTitle,n.CollegeDepartId);

    Option的参数就是依据他们的。

    最后重要的是:
    类上方添加的
    [ScriptService]
    必须添加,否则ajax无法调用WebService

    本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/shuilv2000/archive/2009/02/20/3914822.aspx

    $.ajax(properties)
    使用HTTP请求(XMLHttpRequest)载入一个远程页面。 这是jQuery的低级AJAX实现。要查看高级抽象,见$.set、$.post等。 $.ajax()返回创建好的XMLHttpRequest对象。多数情况下并不需要直接操纵这个对象,但是如果需要手动中止请求,它也是可用的。 注意:要确保服务器返回正确的MIME类型(例如:XML是“text/xml”)。如果返回了错误的MIME类型就会导致jQuery无法处理的严重问题。

    支持的数据类型包括(见dataType选项):

     "xml": 返回一个可以由jQuery对象处理的XML文档。

    "html": 返回纯文本格式的HTML,包括求值后的脚本标记。

    "script": 将响应作为Javascript语句求值,并返回纯文本。

    "json": 将响应作为JSON求值,并返回一个Javascript对象。

    $.ajax()带有一个参数--“名/值对”形式的一个对象,用于初始化和处理请求。

    以下就是可用的所有“名/值对”:

    (String) url - 要将请求发送到的URL地址。

    (String) type - 请求的类型 ("POST" 或 "GET"), 默认是 "GET"。

    (String) dataType - 期望从服务器端返回的数据类型。无默认值:如果服务器返回XML,就将responseXML传递到回调函数,否则将resposeText传递到回调函数。

     (Boolean) ifModified - 只有响应自上次请求后被修改过才承认是成功的请求。是通过检查头部的Last-Modified值实现的。默认值为false,即忽略

    对部分的检查 (Number) timeout - 覆盖全局延迟的局部延迟,例如,在其他所有延迟经过1秒钟后,启动一个较长延迟的单独请求。有关全局延迟,见$.ajaxTimeout()。

     (Boolean) global - 是否为当前的请求触发全局AJAX事件处理函数,默认值为true。设置为false可以防止触发像ajaxStart或ajaxStop这样的全局事件处理函数。

     (Function) error - 当请求失败时调用的函数。这个函数会得到三个参数:XMLHttpRequest对象、一个描述所发生的错误类型的字符串和一个可选异常对象(如果有)。

     (Function) success - 当请求成功时调用的函数。这个函数会得到一个参数:从服务器返回的数据(根据“dataType”进行了格式化)。 (Function) complete - 当请求完成时调用的函数。这个函数会得到两个参数:XMLHttpRequest对象和一个描述请求成功的类型的字符串。

     (Object|String) data - 要发送到服务器的数据。如果还不是一个字符串,就自动轮换为一个查询字符串。即附加到GET请求的url后面的字符串。要防止自动处理见processData选项。

     (String) contentType - 设置发送请求的content=type。默认值是 "application/x-www-form-urlencoded", 这个值能满足多数情况。

     (Boolean) processData - 在默认的情况下,如果data选项传进的数据是一个对象而不是字符串,将会自动地被处理和转换成一个查询字符串,以适应默认的content-type--"application/x-www-form-urlencoded"。如果想发送DOMDocuments,就要把这个选项设置为false。

     (Boolean) async - 在默认的情况下,所有请求都是以异步的方式发送的(值为true)。如果要使用同步方式,需要将此项设置为false。 (Function) beforeSend - 用于设置自定义头部等信息的预调用函数,接收一个唯一的参数--XMLHttpRequest对象。

    Load a remote page using an HTTP request. This is jQuery's low-level AJAX implementation. See $.get, $.post etc. for higher-level abstractions. $.ajax() returns the XMLHttpRequest that it creates. In most cases you won't need that object to manipulate directly, but it is available if you need to abort the request manually. Note: Make sure the server sends the right mimetype (eg. xml as "text/xml"). Sending the wrong mimetype will get you into serious trouble that jQuery can't solve. Supported datatypes are (see dataType option): "xml": Returns a XML document that can be processed via jQuery. "html": Returns HTML as plain text, included script tags are evaluated. "script": Evaluates the response as Javascript and returns it as plain text. "json": Evaluates the response as JSON and returns a Javascript Object $.ajax() takes one argument, an object of key/value pairs, that are used to initalize and handle the request. These are all the key/values that can be used: (String) url - The URL to request. (String) type - The type of request to make ("POST" or "GET"), default is "GET". (String) dataType - The type of data that you're expecting back from the server. No default: If the server sends xml, the responseXML, otherwise the responseText is passed to the success callback. (Boolean) ifModified - Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header. (Number) timeout - Local timeout to override global timeout, eg. to give a single request a longer timeout while all others timeout after 1 second. See $.ajaxTimeout() for global timeouts. (Boolean) global - Whether to trigger global AJAX event handlers for this request, default is true. Set to false to prevent that global handlers like ajaxStart or ajaxStop are triggered. (Function) error - A function to be called if the request fails. The function gets passed tree arguments: The XMLHttpRequest object, a string describing the type of error that occurred and an optional exception object, if one occured. (Function) success - A function to be called if the request succeeds. The function gets passed one argument: The data returned from the server, formatted according to the 'dataType' parameter. (Function) complete - A function to be called when the request finishes. The function gets passed two arguments: The XMLHttpRequest object and a string describing the type of success of the request. (Object|String) data - Data to be sent to the server. Converted to a query string, if not already a string. Is appended to the url for GET-requests. See processData option to prevent this automatic processing. (String) contentType - When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded", which is fine for most cases. (Boolean) processData - By default, data passed in to the data option as an object other as string will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send DOMDocuments, set this option to false. (Boolean) async - By default, all requests are send asynchronous (set to true). If you need synchronous requests, set this option to false. (Function) beforeSend - A pre-callback to set custom headers etc., the XMLHttpRequest is passed as the only argument.

    返回值
    XMLHttpRequest

    参数
    properties (Map): Key/value pairs to initialize the request with.
    示例
    说明:
    载入并执行一个JavaScript文件。

    jQuery 代码:
    $.ajax({ type: "GET", url: "test.js", dataType: "script" })
     
    --------------------------------------------------------------------------------

    说明:
    将数据保存到服务器,并在保存完成后通报用户。

    jQuery 代码:
    $.ajax({ type: "POST", url: "some.php", data: "name=John&location=Boston", success: function(msg){ alert( "Data Saved: " + msg ); } });
     
    --------------------------------------------------------------------------------

    说明:
    同步载入数据。当请求处于活动期间阻塞浏览器。如果必须同步载入数据,最好是通过其他手段来阻止用户的交互,而不是阻塞整个浏览器。

    jQuery 代码:
    var html = $.ajax({ url: "some.php", async: false }).responseText;
     
    --------------------------------------------------------------------------------

    说明:
    将一个XML文档作为数据发送到服务器。通过将processData选项设置为false,可以避免把自动把数据转换为字符串。

    jQuery 代码:
    var xmlDocument = [create xml document]; $.ajax({ url: "page.php", processData: false, data: xmlDocument, success: handleResponse });


    本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/shuilv2000/archive/2009/11/24/4860787.aspx

  • 相关阅读:
    RDMA技术详解(二):RDMA Send Receive操作
    RDMA技术详解(一):RDMA概述
    Fedora中制作UEFI/BIOS启动的U盘安装盘
    Fedora中制作BIOS启动的U盘安装盘
    chkdsk /f
    单片机原理及应用---实验计划
    LeetCode 645. Set Mismatch(错误的集合)
    LeetCode 401. Binary Watch(二进制手表)
    LeetCode 852. Peak Index in a Mountain Array(山脉数组的峰顶索引)
    LeetCode 518. Coin Change 2(零钱兑换 II)
  • 原文地址:https://www.cnblogs.com/tangself/p/1624148.html
Copyright © 2011-2022 走看看