如何从Ajax成功数据功能中获取价值

时间:2019-02-27 22:59:08

标签: asp.net ajax

我的Ajax数据函数具有数据,但是我不知道如何获取该数据并将其插入ID为FirstName的文本框中。我知道数据存在,因为我可以调试并看到“ d”包含查询中的所有数据,但是如何从成功函数中提取数据呢?

$(document).ready(function () {
$("#btnGetData").click(function () {        
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "Default.aspx/GetFormData", //Default.aspx is page and GetFormData is the WebMethod  
        data: {},
        dataType: "json",
        success: function (data) {
            data: { ("#FirstName").val(d.FirstName) }            
        },            
        error: function () {
            alert("Error while Showing update data");
        }
    });
});
});

WebMethod:

public static List<MembersClass> GetFormData()
{

    List<MembersClass> infoObjs = new List<MembersClass>();
    try
    {
        // Initialization.
        string cs = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

        using (SqlConnection con = new SqlConnection(cs))
        {
            SqlCommand cmd = new SqlCommand("dbo.spGetMemberbyMemberID", con);
            cmd.Parameters.AddWithValue("@MemberID", "123");
            cmd.CommandType = CommandType.StoredProcedure;
            con.Open();
            SqlDataReader rdr = cmd.ExecuteReader();

            // Read file.
            while (rdr.Read())
            {
                MembersClass infoObj = new MembersClass();
                infoObj.FirstName = rdr["first_name"].ToString();
                infoObj.LastName = rdr["last_name"].ToString();

                // Adding.
                infoObjs.Add(infoObj);

            }
        }
    }
    catch (Exception ex)
    {
        Console.Write(ex);
    }

    // info.
    return infoObjs;
}

2 个答案:

答案 0 :(得分:0)

我不确定您的响应对象是什么样的,但是尝试一下。

success: function (data) {
    $('#FirstName').val(data.d.FirstName);         
}

答案 1 :(得分:0)

我找到了解决方案。现在,这是从Web方法中获取值并将其放入表单中的。

$(document).ready(function () {
$("#btnGetData").click(function () {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "Default.aspx/GetFormData", //Default.aspx is page and GetFormData is the WebMethod  
        data: {},
        dataType: "json",
        success: function (data) {
            var formdata = $(data.d);
            $.each(formdata, function (index, value) { 
                $("#FirstName").val(value.FirstName);
                $("#LastName").val(value.LastName);
            });
        },
        error: function () {
            alert("Error while Showing update data");
        }
    });
});
});