代码之家  ›  专栏  ›  技术社区  ›  The Muffin Man

使用jquery使用.net web服务

  •  2
  • The Muffin Man  · 技术社区  · 14 年前

    我制作了这个web服务,它从sql server db返回一个数据表。有人能帮我用jquery来显示它吗?

    web服务

    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    
    [ScriptService]
    public class WebService : System.Web.Services.WebService
    {
      DataTable dt = new DataTable();
    
      [WebMethod]
      public DataTable dbAccess()
      {
        using (SqlConnection conn = new SqlConnection(
                ConfigurationManager.ConnectionStrings["localConnectionString"]
               .ConnectionString))
        {
          using (SqlDataAdapter da = new SqlDataAdapter())
          {
            conn.Open();
            da.SelectCommand = 
                 new SqlCommand("SELECT VehicleMake FROM VehicleMakes", conn);
            da.Fill(dt);  
          }
          conn.Close();
        }
        return dt;   
      }   
    }
    

    这是我用jquery得到的

    <script type="text/javascript">
    
        $(function () {
            $('#Button1').click(getData);
        });
    
        function getData() {
            $.ajax({
                type: "POST",
                url: "WebService.asmx/dbAccess",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    // What goes here?
                },
                failure: function (msg) {
                    //error message
                }
            });
        }
    </script>
    
    4 回复  |  直到 14 年前
        1
  •  3
  •   markt    14 年前

    过去,在jQuery中使用asmx服务时,我对post/json使用了如下内容:

    假设我有一个这样的响应类:

        public ResponseClass
        {
            public string Message { get; set; }
        }
    

    以及具有如下方法的webservice:

        [WebMethod]
        [ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
        public ResponseClass PostResponse()
        {
            var response = new ResponseClass() {Message = "Hello World"};
            return response;
        }
    

    一些像这样的html:

    <div id="response">
    </div>
    

    javascript:

    $.ajax({
        url: '/MyService.asmx/PostResponse',
        data: "{}",
        type: "POST",
        cache: false,
        dataType: 'json',
        contentType: "application/json; charset=utf-8",
        success: function(msg) {
            var response = msg.d; //your response object
            $('#response').html(response.Message); //set the response div contents to the Message 
        },
        error: function(xhr, status, error) {
            alert(error); //do something if there is an error
        }
    });
    
        2
  •  1
  •   The Muffin Man    14 年前

    以防有人来找我提供的答案。

    我的web服务与数据库通信,用SqlDataReader读取表,并将该数据加载到data table中。然后每一行存储在一个ArrayList中。

       [WebService(Namespace = "http://babyUnicorns.net/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    
    [ScriptService]
    public class WebService : System.Web.Services.WebService
    {
        [WebMethod]
        public object dbAccess()
        {
    
            DataTable table = new DataTable("myTable");
            ArrayList arl = new ArrayList();
            using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["localConnectionString"].ConnectionString))
            { 
                using(SqlCommand comm = new SqlCommand("SELECT * FROM VehicleMakes",conn))
                {
                    conn.Open();
                    SqlDataReader reader = comm.ExecuteReader();
                    table.Load(reader);
                    reader.Close();
                    conn.Close();    
                }            
            }
            foreach(DataRow dRow in table.Rows)
                    {
                        arl.Add(dRow["VehicleMake"]+"  "+dRow["VehicleMakeId"]);    
                    }
            return arl.ToArray();       
        }  
    }
    

    使用jQuery ajax命令,我将返回的arrayList和foreach项追加到名为“output”的div中。jQuery$。每个命令都用于分离数组。我通过阅读API了解了如何使用它。

        function getData() {
                $.ajax({
                    type: "POST",
                    url: "WebService.asmx/dbAccess",
                    data: "{}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        var response = msg.d;
                        $.each(response, function(index, value) {
                            $('#output').append(value+'<br />'); 
                            });              
                    },
                    failure: function (msg) {
                        alert('failure');
                    }
                });
            }
    </script>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
        <input type="button" id="Button1" value="Get Cars" /><input type="button" id="buttonClear" value="Clear" />
    <div id="output">
    
    </div>
        </div>
        </form>
    </body>
    </html>
    

    这将返回从数据库中提取的汽车列表。

        3
  •  1
  •   Alfred redcoder    13 年前
    <input id="Button2" type="button" value="button" onclick="Find()" /><br /> // call the javascript function Find()
    
    //Javascript function Find()
    function Find() {
            $(document).ready(function () {
                $.ajax(
                {
                    type: "POST",
                    url: "Model/CustomerDTO.asmx/GetDetail",
                    data: "{'nm':'" + $('#Text1').val() + "'}", // passing a parameter to retrive detail.
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                                         var obj = jQuery.parseJSON(msg.d); // parsing of Json string to Javascript object.
                        alert(obj.COMPANYADDRESS); //. anything(depends upon your Fieldname
                        $('#RSSContent').html(obj.COMPANYADDRESS); // bind data to a div
    
                    },
                    error: function () {
                        alert('data could not be be found');
                    }
                });
            });
    
        }
    
        4
  •  0
  •   kobe    14 年前

    你有多种选择

    1) 您可以从后端返回纯html并在div标记上返回do.html

    2) 使用stringbuild构造jsonp对象并返回UI。在用户界面中可以使用 评估(响应)并分析对象。

    如果你需要更多的信息请告诉我。

    两种方法我都做过。

    这是我的代码,你可以这样做

    var jsonobj = eval('(' + tempstr + ')');
    
                for (var i = 0; i < jsonobj.searchsuggest.items.item.length; i++) { }