如何获取数组值从webmethod到jquery显示

本文关键字:webmethod jquery 显示 数组 何获取 获取 | 更新日期: 2023-09-27 18:09:57

我想在一定的时间间隔上显示数据库中的数据,所以我使用了Timer控件,但是在每个tick点上触发div(聊天框)最小化,所以我想避免这种最小化在每个帖子上,我使用Jquery来webmethode概念如下。

调用c#数组类型webmethod。

<script type="text/javascript">
        $(document).ready(function () {           
            $("#tblCustomers tbody tr").remove();
            $.ajax({
                type: "POST",
                url: "GetDataByJquery.aspx/GetMessages",
                data: '{roomId: "' + $("[id$=lblRoomId]").html() + '" }',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    response($.map(data.d, function (item) {
                        var rows = "<tr>"
                    + "<td class='customertd'>" + item.Username + "</td>"
                    + "<td class='customertd'>" + item.Sex + "</td>"
                    + "<td class='customertd'>" + item.Text + "</td>"
                    + "<td class='customertd'>" + item.TimeStamp + "</td>"
                    + "<td class='customertd'>" + item.UserID + "</td>"
                    + "</tr>";
                        $('#tblCustomers tbody').append(rows);
                    }))
                },
                failure: function (response) {
                    alert(response.d);
                }
            });
        });    
    </script>

从sqlserver获取数据并返回数组

    public static Messages[] GetMessages(string roomId)
    {
        List<Messages> messages = new List<Messages>();           
        string strConnString = ConfigurationManager.ConnectionStrings["LinqChatConnectionString"].ConnectionString;
        using (SqlConnection con = new SqlConnection(strConnString))
        {
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                string query = "[Get_Messages]";
                SqlCommand cmd = new SqlCommand(query);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@roomId", roomId);
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    Messages message = new Messages();
                    message.Username = reader.GetString(0);
                    message.Sex = reader.GetString(1);
                    message.Text = reader.GetString(2);
                    message.TimeStamp = reader.GetDateTime(3);
                    message.UserID = reader.GetInt32(4);
                    messages.Add(message);
                }
            }
        }
        return messages.ToArray();
    }

但是我不能显示数据..那么如何显示它?

如何获取数组值从webmethod到jquery显示

使用Newtonsoft。将Object序列化为Json。

设置响应内容类型为application/json,序列化结果对象并返回。

    HttpContext.Current.Response.ContentType = "application/json";
    var result= JsonConvert.SerializeObject(messages);
    return result;

安装Newtonsoft。Json

右键单击解决方案资源管理器中的参考资料文件夹,选择"Manage Nuget Packages",会出现一个向导。

在搜索框中输入Newtonsoft,会显示Json。网在上面

点击Install,它将需要几秒钟来安装

问题不是关于WebMethod,它是当数据返回到客户端,即在$。你没有正确地使用$.map函数,你也使用了未定义的方法response(这个方法在你的代码中不存在),这导致JS错误,数据不显示

所以修改代码

success: function (data) {
   response($.map(data.d, function (item) {
      var rows = "<tr>"
      + "<td class='customertd'>" + item.Username + "</td>"
      + "<td class='customertd'>" + item.Sex + "</td>"
      + "<td class='customertd'>" + item.Text + "</td>"
      + "<td class='customertd'>" + item.TimeStamp + "</td>"
      + "<td class='customertd'>" + item.UserID + "</td>"
      + "</tr>";
      $('#tblCustomers tbody').append(rows);
     }))
  }

success: function (data) {
   var rows = $.map(data.d, function (item) {
      return "<tr>"
      + "<td class='customertd'>" + item.Username + "</td>"
      + "<td class='customertd'>" + item.Sex + "</td>"
      + "<td class='customertd'>" + item.Text + "</td>"
      + "<td class='customertd'>" + item.TimeStamp + "</td>"
      + "<td class='customertd'>" + item.UserID + "</td>"
      + "</tr>";
    });
    $('#tblCustomers tbody').append(rows);
 }

代码说明:

$.map函数用于将集合转换为另一个集合。所以我们正在data.d上工作,对于每次迭代,我们将对象转换为包含一行的html,并在$中返回该html tr行。映射函数体,我们将所有返回的tr HTML存储在一个局部变量" var rows=…"中。

因此,当$.map退出时,我们将所有的tr html转换为可变行,并且我们可以将其附加到表的tbody中,这将导致以表格式显示的数据

您也可以像下面的代码那样使用JsonResult来返回序列化对象。

    [WebMethod]
    public JsonResult testmethod()
    {
        List<YourObject> objectlist = new List<YourObject>();
        JsonResult result = new JsonResult();
        result.Data = objectlist;
        return result;
    }