Ajax realizes intelligent prompt search function

Time:2020-5-22

1、 Renderings:

2、 Implementation process: 

Ideas:

3、 Part code:
html:


 <div>
  <div><input type="text" /></div>
  <div><a href="javascript:;">Google</a></div>
 </div>
 <div></div>  

CSS code:


* {
 padding:0px;
 margin:0px;
}

#searchbox {
 margin-top:10px;
 height:37px;
 width:550px;
}
#searchbox div {
 float:left;
} 
#txtTitle {
 height:35px;
 width:440px;
 line-height:35px;
 border:solid 1px #4791FF;
}
#btnSelect a{
 width:100px;
 height:37px;
 background:#167ED9;
 display:block;
 line-height:37px;
 color:#ffffff;
 text-align:center; 
}
a:link {
 text-decoration:none;
}
a:hover {
 cursor:pointer;
}
#dtitles {
 width:540px;
 height:90px;
 border:solid 1px #CCCCCC;
 display:none;
 font-size:12px;
}
.li1 {
 background:#F0F0F0;
}

JS code:

$(function ()
{
 //1. After the page is loaded, find the content of the text box and trigger an event on it
 $("#txtTitle").keyup(function ()
 {
  //2. Get the content of the text box, and remove the space
  var title = $.trim($("#txtTitle").val());
  //3. After getting the input content, it will be transmitted to the background through Ajax
  $.post("/Handler3.ashx", { "title": title }, function (data)
  {
   if (title == "") {
    $("#dtitles").hide();
   }
   else
   {
    //Display display div, clear it
    $("#dtitles").show().html("");
    if (data == "") {
     $("dtitles"). Text ("no data!");
    }
    else {
     $("#dtitles").append(data);
     //4. After the mouse is moved up, add a background
     $("li").hover(function ()
     {
      $(this).addClass("li1");
     }, function ()
     {
      $(this).removeClass("li1");
     });
    }
   }
  });
 });
});

ajax:

public void ProcessRequest(HttpContext context)
  {
   //1. After submission, we will receive
   string title=context.Request.Form["title"];
   //2. Get an SQL statement
   string strsql = string.Format("select top 5 title from RNews where Title like '%{0}%' ",title);
   //3. How to deal with SQL?
   DataTable dt = SqlHelper.ExecuteDataSetText(strsql,null).Tables[0];
   //4. The last thing we want to return is a list. We need to do string splicing
   StringBuilder sb = new StringBuilder();
   //4.1 judge whether there is data in the SQL result
   if (dt.Rows.Count > 0)
   {
    //4.1.1
    sb.Append("<ul>");
    for (int i = 0; i < dt.Rows.Count; i++)
    {
     sb.Append(string.Format("<li>{0}</li>", dt.Rows[i][0].ToString()));
    }
    sb.Append("</ul>");
   }
   context.Response.Write(sb.ToString());
  }

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.