开发者

consume .net web service using jquery

开发者 https://www.devze.com 2023-01-24 20:38 出处:网络
I made this web service that returns a datatable from sql server db. Can someone help me with the jquery to display it?

I made this web service that returns a datatable from sql server db. Can someone help me with the jquery to display it?

web service

[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;   
  }   
}

and this is as far as I got with the 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>


In the past, when using asmx services with jQuery, I used something like the following for post/json:

Assuming that I had a response class like this:

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

And a webservice with a method like this:

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

Some html like this:

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

The 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
    }
});


Just in case anyone comes by this post looking for the same answer I have provided what I came up with.

My web service communicates with a database, reads a table with a SqlDataReader and loads that data into a datatable. Each row is then stored in an 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();       
    }  
}

Using jQuery ajax command I take the returned arrayList and foreach item in the array I append to my div named "output". The jQuery $.each command is used to pick apart an array. I figured out how to use it by reading the 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>

This returns a list of cars pulled from the database.


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

    }


You have multiple options

1) You can either return pure html from the back end and do .html on the div tag

2) Construct a jsonp object using stringbuild and return to the UI. In the UI you can use eval(response) and parse the object.

Let me know if you need any furthur info on this.

I have done both the approaches.

this is form my code , and you can do as below

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

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号