Imitation Taobao search related quantity instance code

Source: Internet
Author: User
Tags eval keyword list

One, the realization effect analysis
The effect I'm going to achieve is similar to Google, which needs to meet 3 requirements (because I think it's the best user experience, after all, Google has been doing it for so long):
, first list keyword-related information based on keywords (including statistics)
, you can use the keyboard up and down key selection (the default does not select the first), text box content based on the selection of information transformation
, when the first or last one is selected, then the top or bottom is unchecked. The contents of the text box are restored back to the original input (this is important, jingdong this is not good, because when the process of selecting up and down because the text box content will be replaced, so you can not revert to the original user input content)

Second, the Concrete realization analysis
First of all, because the specific data from the database tutorial, so first set up a table in the database to store the search history, each user query is actually the database of the table records (that is, the last query this keyword record number)
Copy code code as follows: CREATE TABLE [dbo]. [T_keywordsearchhistory] (
[Keyword] [nvarchar] (128) Primary key,--keywords
[Count] [INT] Not NULL--number of searches
[RecordCount] [INT] Not NULL--number of records that match keywords
)

The table above is used only to store keywords for user searches. Then in the search of stored procedures or SQL statements in the corresponding processing, when the user entered the keyword in the page and then click the search at this time need to first be based on the keyword in the database to retrieve the corresponding data, if this keyword has relevant data to the T_ The Keywordsearchhistory table adds a new piece of data (if this keyword is already in this table, update the number of searches and the number of records that match the keyword)
copy code as follows:
-The above is a specific SQL query code (number of items that tally with keywords
if @ Recordcount>0
Begin
If @keyword <> '
begin
If exists (select keyword from t_keywordsearchhist Ory where keyword= @keyword)
Begin
Update t_keywordsearchhistory set
recordcount=recordcount+1,
RECORDC ount= @recordCount
where keyword= @keyword
End
Else
begin
INSERT INTO t_keywordsearchhistory values (@keyword, 1, @recordCount)
End
End
End
Else
begin
Update t_keywordsearchhistory set count=count+1,
recordcount= @re Cordcount
where keyword= @keyword
End

After the relevant code for the database has been completed, it is the interface, first of all, the Jquery.autocomplete invocation method:
Copy the Code code as follows: jquery (function () {
JQuery ("#txtKeyword"). AutoComplete ("<%=me.page.resolveclienturl (" ~/service.asmx/autocomplete ")%>", {
HttpMethod: POST,// Use post to invoke WebService
DataType: ' xml ',//Return data type is XML
minchar:1,//minimum response character quantity
selectfirst:false,//default uncheck 1th
/ /formatting options, because the data returned by WebService is in JSON format, now you want to turn HTML to display the
Formatitem:function (row,i,max) {
var obj=eval ("(" +row+) in table format. )//Converts JSON to an object
var item= "<table id= ' Auto" +i+ "' style= ' width:100%;" >
<tr>
<td align= ' left ' > ' +obj.value+ ' </td>
<td align= ' right ' style= ' Color:green ' > "+obj.num+" </td>
</tr>
</table> ";
return item;
},
//formatted result, returns a specific value when selected
Formatresult:function (row,i,max) {
var obj=eval ("(" +row+) ");
return obj.value;
}
});
});

WebService Code:
Copy code code as follows: [WebMethod ()]
Public string[] Getgoodsautocomplete (String q)
{
list<string> list = new list<string> ();
View sourceprint?01//json format template, separated by newline character, processed in JS script
String template = ' {{value: ' {0} ', num: ' {1} '}} ' + system.environment.newline;//+ ' n '
SqlCommand cmd = new SqlCommand ();
SqlDataReader reader = null;
Cmd.commandtext = "Getautocomplete";
Cmd.commandtype = CommandType.StoredProcedure;
Cmd. Parameters.Add ("@keyword", SqlDbType.NVarChar, 128). Value = q;
try {
Reader = Tools.Data.SqlServerHelper.GetReader (volkhelper.getdbconnstring (), CMD);
if (reader!= null) {
while (reader. Read ()) {
string s = String. Format (template, (string) reader ("keyword"), "approx" + (string) reader ("num") + "item");
List. ADD (s);
}
}
}
catch (Exception ex) {

}
Return list. ToArray ();
}

The next is my modified jQuery.AutoComplete.js, because the code is too long, I have already added a download link in the end of the article so that the code is not all posted, only paste my modified place:

Copy code code as follows: function Moveselect (step) {
Listitems.slice (Active, active + 1). Removeclass (CLASSES. ACTIVE);
Moveposition (step);
var Activeitem = Listitems.slice (Active, active + 1). addclass (CLASSES. ACTIVE);
Restores user-entered values when an Action object is empty
if (activeitem[0]!= null | | activeitem[0]!= undefined) {
Input.value = JQuery (activeitem[0]). Find ("Td:first"). Text ();
}
if (active >= 0) {
if (Options.scroll) {
var offset = 0;
Listitems.slice (0, active). each (function () {
Offset + + this.offsetheight;
});
if (offset + activeitem[0].offsetheight-list.scrolltop ()) > List[0].clientheight) {
List.scrolltop (offset + activeitem[0].offsetheight-list.innerheight ());
else if (offset < list.scrolltop ()) {
List.scrolltop (offset);
}
}
}
};
function Moveposition (step) {
if (Active < 0 && Step = = 1) {
active = Listitems.size ()-1;
Return
}
Active + = step;
Restore user-entered values when the cursor is no longer listed
if (Active < 0) {
active =-1;
Input.value = OldValue;
Return
}
Restore user entered values when the keyword list is exceeded
if (Active >= listitems.size ()) {
active =-1;
Input.value = OldValue;
Return
}
}

Started with line 684:
Copy code code as follows: Next:function () {
if (active = = 1) {
OldValue = input.value;//The value entered by the user into a specified variable at the beginning
}
Moveselect (1);
},
Prev:function () {
if (active = = 1) {
OldValue = Input.value;
}
Moveselect (-1);
},

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.