Lucene Hot words display and select

Source: Internet
Author: User
Tags jquery ui autocomplete

Asynchronous request with AutoComplete (1.10.0 version) in jquery Easyui (remot.html)

Add Reference

<script src= "~/scripts/jquery-1.7.1.min.js" ></script>
<script src= "~/scripts/jquery-ui-1.8.20.min.js" ></script>
<link href= "~/content/themes/base/jquery.ui.all.css" rel= "stylesheet"/>

<input type= "text" value= "@ViewData [" Searchwhere "]" name= "txtcontent" autocomplete= "Off" class= "Search-text2" id= "Searchtxtcontent"/>

Asynchronously invokes the AutoComplete of the search controller

<script type= "Text/javascript" >$ (function  () {$ ("#searchTxtContent""/ Search/autocomplete "});});
</script>

In the controller definition method

  #region Search Hot Word public          actionresult AutoComplete ()        {            string term = request["term"];           List<string>list=Keywordsrankservice.getsearchword (term);            return Json (list. ToArray (), jsonrequestbehavior.allowget);        }         #endregion

Defining Query Database Methods

 /// <summary>        ///return hot Words/// </summary>        /// <param name= "str" ></param>        /// <returns></returns>         Publiclist<string> Getsearchword (stringstr) {            stringsql ="Select KeyWords from Keywordsrank where KeyWords like @msg"; return   This. getcurrentdbsession.executeselectquery<string> (SQL,NewSqlParameter ("@msg", str+"%")); }

Defined in Dbsession

 Public List<t> executeselectquery<t> (stringparams  system.data.sqlclient.sqlparameter[ ] {pars        )            {return db.database.sqlquery<t>(SQL, pars). ToList ();        }

-----------------------------jquery AutoComplete Auto-Complete-----------------------------------------------------------------------

Supported data sources
JQuery UI AutoComplete primarily supports string array, json two data formats.
There is nothing special about the normal array format, as follows:
. The code is as follows: ["Cnblogs", "Blog Park", "embarrassing month"]
For an array in JSON format, the following is required: Label, Value property, as follows:
. The code is as follows: [{label: "blog Park", Value: "Cnblogs"}, {label: "Embarrassing Month", Value: "Embarrassing Month"}]
Where the Label property is used to display the AutoComplete pop-up menu, and the Value property is selected to assign to the text box.
If you do not specify one of the properties, replace it with another attribute (that is, value and label value), as follows:
. The code is as follows:
[{label: ' Cnblogs '}, {label: ' Embarrassing Month '}]
[{value: ' Cnblogs '}, {value: ' Embarrassed month '}]

If neither label nor value is specified, you cannot use the hint for AutoComplete.
It is also important to note that the key for the JSON output from the server side must be in double quotes, as follows:
. The code is as follows: [{"label": "Blog Park", "Value": "Cnblogs"}, {"label": "Embarrassed Month", "value": "Embarrassed Month"}]
Otherwise, a parsererror error may occur.
The main parameters
The common parameters of JQuery UI autocomplete are:
Source: Used to specify the data source, type string, Array, Function
String: Server-side address for Ajax requests, return Array/json format
Array: string arrays or JSON arrays
Function (Request, Response): Obtains the input value by Request.term, response ([Array]) to render the data; (Jsonp is this way)
MinLength: Activates autocomplete when the string length in the input box reaches MinLength
AutoFocus: When the AutoComplete selection menu pops up, the first one is automatically selected
Delay: That is, how many milliseconds are delayed to activate AutoComplete
Other infrequently used is not listed.
How to use
If you have the following input boxes on the page:
<input type= "text" id= "Autocomp"/>
Ajax requests
This is done by specifying the source as the server-side address, as follows:
. The code is as follows:
$ ("#autocomp"). AutoComplete ({
Source: "Remote.ashx",
Minlength:2
});

Then receive it on the server side and output the corresponding results, noting that the default pass parameter name is term:
. The code is as follows:
public void ProcessRequest (HttpContext context)
{
The parameter name of the query defaults to term
String query = Context. request.querystring["term"];
Context. Response.ContentType = "Text/javascript";
An array of output strings or a JSON array
Context. Response.Write ("[{\" label\ ": \" blog garden \ ", \" value\ ": \" Cnblogs\ "},{\" label\ ": \" embarrassed month \ ", \" value\ ": \" embarrassed month \ "}]");
}

Local Array/json Array
. The code is as follows:
Local string array
var availabletags = [
"C #",
"C + +",
"Java",
"JavaScript",
"ASP",
"ASP.",
"JSP",
"PHP",
"Python",
"Ruby"
];
$ ("#local1"). AutoComplete ({
Source:availabletags
});
Local JSON array
var Availabletagsjson = [
{label: "C # Language", Value: "C #"},
{label: "C + + Language", value: "C + +"},
{label: "java Language", Value: "Java"},
{label: "JavaScript Language", Value: "JavaScript"},
{label: "ASP.", Value: "ASP."},
{label: "JSP", Value: "JSP"},
{label: "PHP", Value: "PHP"},
{label: "Python", Value: "Python"},
{label: "Ruby", Value: "Ruby"}
];
$ ("#local2"). AutoComplete ({
Source:availabletagsjson
});

Callback function mode
By specifying source as a custom function for custom data acquisition, the function has 2 parameters (Request,response), which are used to obtain the input value, render the result, respectively.
Local array method to get data (imitating Sina Weibo login)
. The code is as follows:
var hosts = ["gmail.com", "live.com", "hotmail.com", "yahoo.com", "cnblogs.com", "Mars. com", "embarrassing month. com"];
$ ("#email1"). AutoComplete ({
Autofocus:true,
Source:function (Request, Response) {
var term = request.term,//request.term as input string
IX = Term.indexof ("@"),
name = term,//user name
Host = "",//Domain name
result = []; Results
Result.push (term);
Result.push ({label:term, value:term}); JSON format
if (ix >-1) {
Name = Term.slice (0, ix);
Host = Term.slice (ix + 1);
}
if (name) {
var findedhosts = (Host $.grep (Hosts, function (value) {
return Value.indexof (Host) >-1;
}): Hosts),
Findedresults = $.map (findedhosts, function (value) {
Return name + "@" + value; Return string format
return {label:name + "@" + value, Value:name + "@" + value}; JSON format
});
result = Result.concat ($.makearray (findedresults));
}
Response (result);//Render result
}
});

Jsonp Way to get data
Directly from the official demo, by sending Ajax requests to the remote server, and then processing the returned results, and finally through the response to render:
. The code is as follows:
$ ("#jsonp"). AutoComplete ({
Source:function (Request, Response) {
$.ajax ({
URL: "Http://ws.geonames.org/searchJSON",
DataType: "Jsonp",
Data: {
Featureclass: "P",
Style: "Full",
Maxrows:12,
Name_startsWith:request.term
},
Success:function (data) {
Response ($.map (data.geonames, function (item) {
return {
Label:item.name + (item.adminname1? "," + item.adminname1: "") + "," + Item.countryname,
Value:item.name
}
}));
}
});
},
Minlength:2
});

The main event jQuery UI AutoComplete has some events that can be used for additional control at some stage:
Create (event, UI): When AutoComplete is created, you can have some control over the appearance in this event
Search (event, UI): You can return false in this event to cancel the request before the request is started
Open (Event, UI): AutoComplete when the result list pops up
Focus (event, UI): AutoComplete results list when any one of the items gets the focus, the Ui.item is the item that gets the focus
Select (Event, UI): AutoComplete The result list when any item is selected, Ui.item is the selected item
Close (event, UI): When the result list of AutoComplete is closed
Change (event, UI): When the value changes, Ui.item is the selected item
The Item property of the UI parameters for these events, if any, has the label and Value property by default, regardless of whether the data set in source is an array or a JSON, as in the following 3 types:
. The code is as follows:
["Cnblogs", "Blog Park", "embarrassing month"]
[{label: ' Blog Park ', Value: ' Cnblogs '}, {label: ' Embarrassing Month ', value: ' Embarrassing month '}]
[{label: "blog Park", Value: "Cnblogs", ID: "1"}, {label: "Embarrassed Month", value: "Embarrassed month", ID: "2"}]

If it is the third kind, you can also get the value of ui.item.id.
These events can be bound in 2 ways, as follows:
. The code is as follows:
In the parameters
$ ("#autocomp"). AutoComplete ({
Source:availabletags
, Select:function (E, UI) {
Alert (Ui.item.value)
}
});
Bind by Bind
$ ("#autocomp"). Bind ("Autocompleteselect", Function (E, UI) {
alert (Ui.item.value);
});

The event name used in bind by bind is "AutoComplete" + event name, such as "select" is "Autocompleteselect".
AutoComplete of multiple values
In general, the AutoComplete of the input box requires only a single value (such as JavaScript), and if multiple values (such as: javascript,c#,asp.net) are required, some events need to be bound for additional processing:
Returns false in the focus event to prevent the value of the input box from being replaced by a single value of AutoComplete
Combining multiple values in a select event
Do some processing on the element's KeyDown event for the same reason as 1
Use the callback function mode source to get the last value entered and render the result
Or just take the official demo code:
. The code is as follows:
Separate multiple values by commas
Function Split (val) {
Return Val.split (/,\s*/);
}
Extract the last value of an input
function Extractlast (term) {
Return split (term). Pop ();
}
Cancel setting value for the input box when pressing the TAB key
function KeyDown (event) {
if (Event.keycode = = = $.ui.keycode.tab &&
$ (this). Data ("AutoComplete"). Menu.active) {
Event.preventdefault ();
}
}
var options = {
Get focus
Focus:function () {
Prevent value inserted on focus
return false;
},
When selecting a value from the AutoComplete pop-up menu, add to the last of the input box, separated by commas
Select:function (event, UI) {
var terms = split (this.value);
Remove the current input
Terms.pop ();
Add the selected item
Terms.push (Ui.item.value);
Add placeholder to get the comma-and-space at the end
Terms.push ("");
This.value = Terms.join (",");
return false;
}
};
Multiple values, local array
$ ("#local3"). Bind ("KeyDown", KeyDown)
. AutoComplete ($.extend (options, {
Minlength:2,
Source:function (Request, Response) {
Delegate AutoComplete, but extract
Response ($.ui.autocomplete.filter (
Availabletags, Extractlast (request.term)));
}
}));
Multiple values, AJAX returns JSON
$ ("#ajax3"). Bind ("KeyDown", KeyDown)
. AutoComplete ($.extend (options, {
Minlength:2,
Source:function (Request, Response) {
$.getjson ("Remotejson.ashx", {
Term:extractlast (Request.term)
}, Response);
}
}));

Lucene Hot words display and select

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.