使用 ajax 从 web 方法绑定标签

Binding Lable from webmethod using ajax

大家好,我正在尝试从 webmethod 读取数据并将值传递到我在 aspx 页面中的标签。为此,我使用了 Ajax 和网络方法。我的问题是当我无法将成功数据绑定到我的标签控件时。

我的 .asmx 页面。

  public static string str;
  [WebMethod]
    public string GetEmployeeDetail(string name)
    {
        str = name;
        Get(str);
        string daresult;
        daresult = Get(str);
        return daresult;
    }

   [WebMethod]
    public string Get(string str)
    {
        List<string> rst = new List<string>();
        using (SqlConnection con = new SqlConnection("..."))
        {
            using (SqlCommand cmd = new SqlCommand("select practice_short_name from PRACTICE_DETAIL where Practice_Name = '" + str + "'",con))
            {
                con.Open();
                SqlDataReader dr = cmd.ExecuteReader();
                while(dr.Read())
                {
                    rst.Add(string.Format("{0}", dr["practice_short_name"]));

                }
                System.Web.Script.Serialization.JavaScriptSerializer jSearializer =  new System.Web.Script.Serialization.JavaScriptSerializer();
                return jSearializer.Serialize(rst);
            }
        }
    }

这是我在 aspx 页面中的 ajax 调用函数。

 function fun() {
         var ddlpsn = document.getElementById("<%=ddlPSN.ClientID%>");

         $(ddlpsn).change(function () {
             var s = $(this).val();
             $.ajax({
                 type: 'POST',
                 url: 'AutoCompleteService.asmx/GetEmployeeDetail',
                 data: '{name: "' + s + '" }',
                 dataType: 'json',
                 contentType: 'application/json; charset=utf-8',
                 success: function (data) {
               //i think i need to do some changes in here but not getting what to do.
                     $('#lblpriority').text(data.val);
                 },
                 error: function (error) {
                     console.log(error);
                 }
             });
         });
     };

您需要将 data.val 更改为 data.d。如果您没有为返回的数据明确定义自己的 属性,则从 WebMethod 返回的数据包含在 d 属性 中。

$('#lblpriority').text(data.d);

您需要设置 WebMethod static 才能被 ajax 调用。