Jquery自动完成,多个数组作为源

时间:2013-10-31 10:20:04

标签: javascript arrays json jquery-ui autocomplete

我有一个场景,我需要向使用jquery自动填充的搜索社交网络中的医生和医生进行显示,我已成功向医生展示但我无法通过某种方式显示数据从自动完成分类中的两个阵列,以便它显示医生标题下的医生和连接医生在连接标题下但我没有得到如何使用自动完成中的数组。这是我从服务器返回的Json:

    {"connections":
    [{"ConnectionID":"8","ConnectionName":"Saima Fayyaz","ImageName":"201304061217391.5x1.5.jpg"}],
    "doctors":
[{"DoctorID":"4","DoctorName":"Imran Saeed Ali","ImageName":"20130516210722ImranSAli.jpg","Type":"Doctor"},
{"DoctorID":"8","DoctorName":"Saima Fayyaz","ImageName":"201304061217391.5x1.5.jpg","Type":"Doctor"},
{"DoctorID":"10","DoctorName":"Sabira  Javaid","ImageName":"20130406123414123.jpg","Type":"Doctor"}]}

这是我的javascript代码:

<script type= "text/javascript">
$(document).ready(function () {

    $("#people").autocomplete({
        minLength: 0,
        source: function (request, response) {
            $.ajax({
                url: '@Url.Action("Search","SearchPathologist")',
                dataType: "json",
                data: {
                    term: request.term,
                    flag: "all"
                },
                success: function (data) {
                    //alert(data.doctors);
                    response($.map(data.doctors, function (item) {
                        // alert(item.Type);
                        return {
                            //data: item.doctors
                              id: item.DoctorID,
                              name: item.DoctorName,
                              photo: item.ImageName,

                        }
                    }));

                }
            });
        },
        focus: function (event, ui) {

        }

    })
.data("autocomplete")._renderItem = function (ul, item) {

    return $("<li></li>")
    .data("item.autocomplete", item)
    .append("<div style='width:100%; margin:auto; background:white; min-height:20px;'><div style='border-bottom:1px dashed gray;'><div style='float:left;  width:16%; min-height:35px; margin:auto;'><img src='http://olivecliq.com:84/carepoint/doctor_images/"+item.photo+"' width='31px' style='margin-top:4px; margin-left:1px;' /></div><div class='mid_card'><h2> " + item.name + "</h2><h3>Use StrongVPN &amp; have a USA or UK IP address anywhere.</h3></div><div style='float:left;width:10%; min-height:25px; margin:auto;'> <img src='@Url.Content("~/images/arrow.png")' width='25' style='margin-top: 10px;' /></div><div style='clear:both;'></div></div>")
    .appendTo(ul);


});

我真的被困了,任何帮助都会受到赞赏。

1 个答案:

答案 0 :(得分:2)

我做了这样的事情来克服这个问题。

这是jquery代码:

<script type="text/javascript">
$(document).ready(function () {
    var drew = false;
    $("#people").on("keyup", function (event) 
    {
        var query = $("#people").val();

        if ($("#people").val().length >= 1) 
        {
            $('div#loaderContainer').show();
            $.ajax({
                url: '@Url.Action("Search","SearchPathologist")',
                dataType: "json",
                data:
                    {
                        term: query,
                        flag: "all"
                    },
                    error: function()
                    {
                    $.fallr('show', {
        content: '<p>Error occured! May be your session expired.</p>'
                    });
                    },
                success: function (data) 
                {
                    $('div#loaderContainer').hide();
                        //First search
                        if (drew == false) 
                        {
                            //Create list for results
                            $("#people").after("<ul id='res' class='ui-autocomplete ui-menu ui-widget ui-widget-content ui-corner-all' role='listbox' aria-activedescendant='ui-active-menuitem' style='z-index: 10005; display: block; width: 293px;'></ul>");

                            //Prevent redrawing/binding of list
                            drew = true;

                            //Bind click event to list elements in results
                            $("#res").on("click", "li.item", function () 
                            {
                                $("#people").val($(this).text());
                                $("#res").empty();
                            });
                        }
                        //Clear old results
                        else 
                        {
                            $("#res").empty();
                        }



                        $.each(data.doctors, function (i, item) {
                            if(i==0)
                            {
                            $("#res").append("<div id='doctors'></div>")
                            $("#doctors").append("<li style='background: linear-gradient(to bottom, #499BEA 0%, #207CE5 100%) repeat scroll 0 0 rgba(0, 0, 0, 0); margin-left:2px;text-align:center;color:white;'>Doctors</li>");
                            }
                            $("#doctors").append("<li class='item'><div style='width:100%; margin:auto; background:white; min-height:20px;'><div style='border-bottom:1px dashed gray;'><div style='float:left;  width:16%; min-height:35px; margin:auto;'><img src='http://olivecliq.com/carepoint/doctor_images/"+item.ImageName+"' width='31px' style='margin-top:4px; margin-left:1px;' /></div><div class='mid_card'><h2> " + item.DoctorName + "</h2><h3></h3></div><div style='float:left;width:10%; min-height:25px; margin:auto;'> <img src='@Url.Content("~/images/arrow.png")' width='25' style='margin-top: 10px;' /></div><div style='clear:both;'></div></div></li>");
                        });

                        $.each(data.connections, function (i, item) {
                            if(i==0)
                            {
                            $("#res").append("<div id='connections'></div>")
                            $("#connections").append("<li style='background: linear-gradient(to bottom, #499BEA 0%, #207CE5 100%) repeat scroll 0 0 rgba(0, 0, 0, 0); margin-left:2px;text-align:center;color:white;'>Connections</li>");
                            }
                            $("#connections").append("<li class='item'><div style='width:100%; margin:auto; background:white; min-height:20px;'><div style='border-bottom:1px dashed gray;'><div style='float:left;  width:16%; min-height:35px; margin:auto;'><img src='http://olivecliq.com/carepoint/doctor_images/"+item.ImageName+"' width='31px' style='margin-top:4px; margin-left:1px;' /></div><div class='mid_card'><h2> " + item.ConnectionName + "</h2><h3></h3></div><div style='float:left;width:10%; min-height:25px; margin:auto;'> <img src='@Url.Content("~/images/arrow.png")' width='25' style='margin-top: 10px;' /></div><div style='clear:both;'></div></div></li>");
                        });


                    if($('button#searchDDL').html() == "Doctors")
                    {
                    $('div#connections').hide();
                    }
                    if($('button#searchDDL').html() == "Connections")
                   {
                   $('div#doctors').hide();
                   }



                }


            });


        }

        else
        {
        $("#res").empty();
        $( "#res" ).remove();
        drew = false;
        }
    });


          $("input#people").focusout(function () {

$( "#res" ).remove();
drew = false;


});
});
</script>

这是我的HTML:

 <div class="search_input"><input type="text" id="people" placeholder="Search for specialist doctors and more.." />
</div>
<button type="submit" class="search-button" value="Search" name="search">
        <span><img src="@Url.Content("~/images/search-icon.png")" height="20" /></span>
      </button>
</div>

这是我的行动:

public JsonResult Search(string term, string flag)
        {
            using (OliveCliqService.OliveServiceClient client = new OliveCliqService.OliveServiceClient())
            {
                PathWay.OliveCliqService.SearchResult result = new PathWay.OliveCliqService.SearchResult();

                result = client.Search(Session["userID"].ToString(), term, flag);

                return Json(result,JsonRequestBehavior.AllowGet);
            }
        }

这是我的WCF服务方法:

public SearchResult Search(string PersonID,string term,string flag)
        {
            string cmd;
            string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["OliveCliq"].ConnectionString;


            MySqlConnection con = new MySqlConnection(connectionString);
            con.Open();
            cmd = @"SELECT DISTINCT d.DoctorID,
d.FirstName,
d.LastName,
d.Image,
r.name,
s.Spaciality_name,
oc.clinic_name,
cb.Location,
rpd.acronym
FROM doctor_members dm
LEFT OUTER JOIN doctors d on dm.member_id = d.doctorid
LEFT OUTER JOIN clinic_doctor_designations cdd on d.doctorid = cdd.doctor_id
LEFT OUTER JOIN rm_pr_designations de on cdd.designation_id = de.designationid
LEFT OUTER JOIN doctor_spcialities ds on d.doctorID = ds.doctorid
LEFT OUTER JOIN spaciality s on ds.spacialityID = s.id
LEFT OUTER JOIN clinic_doctor_departments dd on dm.member_id = dd.doctor_id
LEFT OUTER JOIN rm_pr_departments r on dd.department_id  = r.departmentid
LEFT OUTER JOIN clinic_doctors cd on dm.member_id = cd.DoctorID
LEFT OUTER JOIN clinic_branches cb on cd.clinic_branch_id = cb.branch_id
LEFT OUTER JOIN clinics oc on cb.clinic_id = oc.id
LEFT OUTER JOIN doctor_education dee on dm.member_id = dee.doctorid
LEFT OUTER JOIN rm_pr_degrees rpd on dee.degreeid = rpd.degreeid
where dm.doctor_id  = '" + PersonID + "' And d.FirstName like '" + term + "%' group by d.DoctorID LIMIT 5";

            MySqlDataAdapter da = new MySqlDataAdapter(cmd, con);

            DataSet ds = new DataSet();

            da.Fill(ds);

            SearchResult result = new SearchResult();

            //List<string> listTest = new List<string>();

            List<Doctor> doctorList = new List<Doctor>();

            List<Connection> connectionList = new List<Connection>();

            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {

                //string test = ds.Tables[0].Rows[i]["TestName"].ToString();

                Connection objConnection = new Connection();

                objConnection.ConnectionID = ds.Tables[0].Rows[i]["DoctorID"].ToString();
                objConnection.ConnectionName = ds.Tables[0].Rows[i]["FirstName"].ToString() + " " + ds.Tables[0].Rows[i]["LastName"].ToString();
                objConnection.ImageName = ds.Tables[0].Rows[i]["Image"].ToString();
                //objConnection.Type = "Connection";
                connectionList.Add(objConnection);
            }

            con.Close();


            cmd = @"SELECT DISTINCT d.DoctorID,
d.FirstName,
d.LastName,
d.Image
FROM doctors d
where (d.FirstName like '"+term+"%') and (d.DoctorID not in ( select dm.member_id FROM doctor_members dm )) LIMIT 5";

            con.Open();

            MySqlDataAdapter da1 = new MySqlDataAdapter(cmd, con);

            DataSet ds1 = new DataSet();

            da1.Fill(ds1);



            //List<string> listTest = new List<string>();

           // List<Doctor> doctorList = new List<Doctor>();

            for (int i = 0; i < ds1.Tables[0].Rows.Count; i++)
            {

                //string test = ds.Tables[0].Rows[i]["TestName"].ToString();

                Doctor objDoctor = new Doctor();

                objDoctor.DoctorID = ds1.Tables[0].Rows[i]["DoctorID"].ToString();
                objDoctor.DoctorName = ds1.Tables[0].Rows[i]["FirstName"].ToString() + " " + ds1.Tables[0].Rows[i]["LastName"].ToString();
                objDoctor.ImageName = ds1.Tables[0].Rows[i]["Image"].ToString();
                objDoctor.Type = "Doctor";
                doctorList.Add(objDoctor);
            }

            result.connections = connectionList;
            result.doctors = doctorList;


            return result;
        }

这是我的SearchResult类:

public class SearchResult
    {
        public List<Doctor> doctors { get; set; }
        public List<Connection> connections { get; set; }
    }

这是我的博士班:

public class Doctor
    {
        public string DoctorID { get; set; }
        public string DoctorName { get; set; }
        public string ImageName { get; set; }
        public string Type { get; set; }
    }

这是我的连接类:

public class Connection
    {
        public string ConnectionID { get; set; }
        public string ConnectionName { get; set; }
        public string ImageName { get; set; }
    }

我还在我的博客上发了一篇教程帖子,详见下面的链接:

http://developmentpassion.blogspot.com/2013/12/facebook-and-linkedin-like-searching.html?m=0