2010-11-14 77 views
2

我做了这个web服务,它从sql server db返回一个数据表。有人可以帮我用jQuery来展示它吗?使用jquery消耗.net web服务

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> 
+0

我想你需要WCF提供JSON数据,如:http://www.west-wind.com/weblog/posts/164419.aspx – 2010-11-14 20:53:29

+1

@Albin,用[ScriptService]属性, web服务将返回JSON,不需要WCF。 – Carson63000 2010-11-14 22:50:59

+0

但是,如何使用JSON获取DataTable并使用JSON获取DataTable的每一行? – 2013-12-02 09:46:46

回答

3

在过去得了,用用jQuery ASMX服务时,我用类似的帖子下面/ json:

假设我有这样的响应类:

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

而且像这样的方法的Web服务:

[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 
    } 
}); 
+1

@nick:这也是我一直这样做的方式。小窍门:如果您使用Firefox和Firebug,Net窗格将显示ajax请求,包括提供响应的JSON视图。在查看如何将精确复杂的类型作为JSON返回时可能会有所帮助。 – Carson63000 2010-11-14 22:52:33

0

你有多种选择

1 )您可以从后端返回纯html并在div标签上执行.html

2)使用stringbuild构造一个jsonp对象并返回到UI。在UI中,您可以使用eval(响应) 并解析对象。

让我知道你是否需要任何有关此的更多信息。

我已经完成了这两种方法。

这是形成我的代码,你可以做如下

var jsonobj = eval('(' + tempstr + ')'); 

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

他已经有他的ScriptService作为JSON返回结果,他不需要自己构造JSON字符串。 – Carson63000 2010-11-14 22:53:10

+0

对不起,我认为他现在没有将方法结果作为jsonp对象公开,是的,最近我做了与WCF一样暴露了作为ajax/jsonp的ressponse。 – kobe 2010-11-14 23:00:14

1

万一有人来通过这篇文章找我所提供的相同的答案是什么,我想出了。

我的Web服务与数据库进行通信,使用SqlDataReader读取表并将该数据加载到数据表中。然后每行存储在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 $ .each命令用于挑选一个数组。我想通过阅读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> 

这将返回从数据库中拉出的汽车列表。

1
<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'); 
       } 
      }); 
     }); 

    }