如何使用ajax调用的结果设置输入文本框

时间:2015-04-07 20:33:17

标签: jquery asp.net asp.net-mvc

需要使用ajax调用的结果自动填充名字和姓氏文本框。这是aspx web表单:

       <input id="firstName" type="text" size="26"  maxlength="20" name="firstName" tabindex="2" />                           
      <input id="lastName" type="text" value="" size="26" maxlength="20" name="lastName" tabindex="4" />

这是带有ajax调用的jquery脚本:

  <script>
    $("#lifeNumber").on('focusout', function (evt) {
        var options = {};
        options.url = "pcfform.aspx/GetEmployees";
        options.data = JSON.stringify({ lifeNumber: $(evt.target).val()  });
        options.type = "POST";
        options.dataType = "json";
        options.contentType = "application/json";
        options.success = function (result) {
           //need help here

            }
        };
        options.error = function (xhr, status, err) {
            alert(err);
        };
        $.ajax(options);
    });
</script>

这是aspx中的WebMethod:

       public class Employee
       {
         public string FirstName { get; set; }
         public string LastName { get; set; }
       }

    [WebMethod]
    public static List<Employee> GetEmployees(string lifeNumber)
    {
        PCF.Entities.Data.Entities db = new PCF.Entities.Data.Entities();
        var data = db.MasterTables
                    .Where(x => x.Life_Hosp == lifeNumber)
                    .Select(x => new Employee
                    {
                        FirstName = x.FirstName,
                        LastName = x.LastName
                    });
        return data.ToList();
    }

1 个答案:

答案 0 :(得分:0)

如果您正在努力使用成功方法,此代码可以帮助您:

$("#lifeNumber").on('focusout', function (evt) {
        var options = {};
        options.url = "pcfform.aspx/GetEmployees";
        options.data = JSON.stringify({ lifeNumber: $(evt.target).val()  });
        options.type = "POST";
        options.dataType = "json";
        options.contentType = "application/json";
        options.success = function (result) {


            $('#firstName').val(result.d[0].FirstName);
            $('#lastName').val(result.d[0].LastName);

            }
        };
        options.error = function (xhr, status, err) {
            alert(err);
        };
        $.ajax(options);
    });