我对jQuery和JSON相当新,遇到了一个我无法解决的问题。我有一个文本框,我希望用户开始输入一个人的姓名,当他/她选择名称时,它会自动填充另一个带有他们电子邮件地址的文本框。
我的代码如下。任何有助于此工作的帮助将不胜感激。非常感谢提前!
标记
<input type="text" id="person_name" class="required" />
<input type="text" id="person_email_address" class="required email" />
的jQuery
$( "input#person_name" ).autocomplete({
source: "/autoComplete.aspx",
dataType: "json",
minLength: 1,
select: function( event, ui ) {
//set email textbox to the email field of the selected item.
}
});
autoComplete.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
string term = Request.QueryString["term"];
if (!string.IsNullOrEmpty(term))
{
string sql = string.Format("select * from users where first_name like '%{0}%' or last_name like '%{0}%'", term);
DataTable dt = GetTable(sql);
foreach (DataRow dr in dt.Rows)
{
string name = dr["first_name"].ToString() + dr["last_name"].ToString();
string email = dr["email"].ToString();
}
Response.ContentType = "application/json";
Response.Write("what goes here so i can access both email and name in the select function?");
}
}
答案 0 :(得分:1)
在代码隐藏中使用类似的内容:
var items = dt.AsEnumerable().Select(
dr => new
{
name = dr["first_name"].ToString() + dr["last_name"].ToString(),
email = dr["email"].ToString()
}
);
string json = "[" + string.Join(",",
items.Select(i =>
"{ id: '" + i.name + "'"
+ ", label: '" + i.name + "'"
+ ", value: '" + i.email + "'"
+ "}"
)
) + "]";
Response.Write(json);
这应该为您提供正确的JSON,其中 name 为标签, email 为值。现在在Javascript选择回调函数中,将电子邮件文本框设置为正确的值:
select: function( event, ui ) {
//set email textbox to the email field of the selected item.
$("#person_email_address") = ui.item.value;
}
注意强>
根据评论,上述内容无需修改即无效。 JSON值必须用双引号括起来。