Jquery ajax retrieves json data to implement Baidu's search tips

Source: Internet
Author: User


Baidu and Google seem to have been doing this for many years. I thought it was easy to find code on the Internet to achieve this effect. We can't find this requirement. Therefore, I wrote this result by myself. Because I integrated the effect into my entire framework, I did not encapsulate it separately.

Requirements:
Implement the input box with prompts, similar to Baidu search. Frequently used keywords are obtained when there are changes. The data comes from the system database and supports mouse selection or keyboard selection.

Ideas:
The framework's consistent thinking is to use class as the listener Portal and data as the data for transmission;
Monitors input and propertychange events for real-time changes. input is the mainstream, and propertychange is ie, you know;
The post action is implemented through ajax, and the returned content is displayed in a format similar to the selected box;
Listen to the keyboard's upper key (38), lower key (40), and enter key (13). By binding the keydown, judge the event. keycode implementation;
Listening to mouse mouseover and click events should be perfectly combined with keyboard actions;
If the input content must be consistent with the known options, listen to the blur event and determine whether to allow focus change;

Implementation code:

// By COoL
 
// Define global variables to store the prompt layer
Var liketips;
 
// Listen for changes or get focus events
 
// Disable automatic prompts in chrome and firefox
$ ('. Getsearchjson'). attr ("autocomplete", "off ");
$ ('. Getsearchjson'). bind ("propertychange input focus", function (event ){
$ This = $ (this );
If (event. type! = 'Focal '){
// If there is a change, the status is set to have to be re-selected, because the value cannot be inserted due to manual input.
$ This. data ('OK', false );
    }
 
// Obtain the location of the input box and calculate the location where the prompt layer should appear
Var top = 1 * $ this. offset (). top + 25;
Var left = 1 * $ this. offset (). left;
Var width = 1 * $ this. width () + 12;
    
// Re-create the storage prompt layer and display it in the appropriate position
$ (Liketips). remove ();
Liketips = document. createElement ('div ');
$ Liketips = $ (liketips );
// Class style is not provided here, mainly position: absolute
$ Liketips. addClass ("liketips ");
$Liketips.css ({top: top + 'px ', left: left + 'px', width: width + 'px '});
 
// Display the loading dynamic diagram before loading
$ Liketips. append (' ');
$ Liketips. appendTo ($ this. parent ());
$ Liketips. show ();
 
// Define ajax to get json. The type parameter is set through data-type, and the keyword parameter is the value already entered
// The returned value is displayed as a table.
$. Post ('/data/search. do ', {type: $ this. data ('type'), keyword: $ this. val ()}, function (json ){
$ Liketips. empty ();
Var htmlcode = "<table cellspacing = '0' cellpadding = '2'> <tbody> ";
For (var I = 0; I <json. datas. length; I ++ ){
// Here I need to use two items: value and title. Therefore, use data-value to pass one more parameter, and assign the value to the corresponding place after pressing the carriage return or mouse, so as to perfectly replace select
Htmlcode + = '<tr data-value = "' + json. datas [I] [0] + '"> <td>' + json. datas [I] [1] + '</td> </tr> ';
        }
Htmlcode + = "</tbody> </table> <span> select </span> ";
// Replace the loading dynamic graph with the content
$Liketips.html (htmlcode );
}, "Json ");
});
 
// When the focus disappears, ensure that the data comes from the options and hide the prompt body.
$ ('. Getsearchjson'). blur (function (){
// Because the blur action is settled before clicking the mouse, setTimeout is used to solve this problem.
$ Oldthis = $ (this );
SetTimeout (function (){
If ($ oldthis. data ('OK '))
$ (Liketips). fadeOut ('quick ');
Else {
Alert ('to ensure data accuracy, please select one from the drop-down prompt. Thank you for your cooperation ');
$ Oldthis. focus ();
        }
},200 );
});
 
// Listen for keyboard actions
$ ('. Getsearchjson'). keydown (function (event ){
// Console. log (event. keyCode );
$ This = $ (this );
If (event. keyCode = 40 ){
// Press down
$ Nowtr = $ ('tr. selectedtr ');
// If selected, go down. Otherwise, select the first one in the menu.
If ($ nowtr. length> 0 ){
$ Nexttr = $ nowtr. next ('tr ')
// If it is not the final option, move the next tr; otherwise, jump to the first tr.
If ($ nexttr. length> 0 ){
$ ('Tr. selectedtr '). removeClass ();
$ Nexttr. addClass ('selectedtr ');
            }
Else {
$ ('Tr. selectedtr '). removeClass ();
$ Nowtr. parent (). find ('tr: first '). addClass ('selectedtr ');
            }
        }
Else {
$ ('. Liketips'). find ('tr: first '). addClass ('selectedtr ');
        }
    }
Else if (event. keyCode = 38 ){
// The Button is up
$ Nowtr = $ ('tr. selectedtr ');
// If selected, go down. Otherwise, select the first one in the menu.
If ($ nowtr. length> 0 ){
$ Prevtr = $ nowtr. prev ('tr ')
// If it is not the final option, move the next tr; otherwise, jump to the first tr.
If ($ prevtr. length> 0 ){
$ ('Tr. selectedtr '). removeClass ();
$ Prevtr. addClass ('selectedtr ');
            }
Else {
$ ('Tr. selectedtr '). removeClass ();
$ Nowtr. parent (). find ('tr: LA'). addClass ('selectedtr ');
            }
        }
Else {
$ ('. Liketips'). find ('tr: LA'). addClass ('selectedtr ');
        }
    }
Else if (event. keyCode = 13 ){
// Press enter to return and hide the selection box.
$ Nowtr = $ ('tr. selectedtr ');
If ($ nowtr. length = 1 ){
// Set the value to the value storage item configured by the data-valueto parameter in the input box. It is generally a hidden item.
$ Valuefield = $ ('input [name = '+ $ this. data ('valueto') + ']');
$ Valuefield. val ($ nowtr. data ('value '));
$ This. val ($ nowtr. text ());
// Set the status to select from options and allow blur
$ This. data ('OK', true );
        }
$ (Liketips). fadeOut ('quick ');
Return false;
    }
// Console. log (event. keyCode );
Return true;
});
 
// Listens to mouse actions, and mouseover changes the selected item
$ (Document). delegate ('. liketips td', 'mouseover', function (){
$ Nowtr = $ (this). parent ();
$ Nowtr. siblings ('tr'). removeClass ();
$ Nowtr. addClass ('selectedtr ');
});
 
// Listen to the mouse action, click to select
$ (Document). delegate ('. liketips td', 'click', function (){
$ Nowtr = $ (this). parent ();
If ($ nowtr. length = 1 ){
// Obtain the input box corresponding to the prompt layer
$ Inputfield = $ nowtr. parent (). siblings ('input. Getsearchjson ');
 
// Set the value to the value storage item configured by the data-valueto parameter in the input box. It is generally a hidden item.
$ Valuefield = $ ('input [name = '+ $ inputfield. data ('valueto') + ']');
$ Valuefield. val ($ nowtr. data ('value '));
$ Inputfield. val ($ nowtr. text ());
// Set the status to select from options and allow blur
$ Inputfield. data ('OK', true );
    }
$ (Liketips). fadeOut ('quick ');
});


CSS will not be released here. My implementation results are as follows:

// Disable automatic prompts in chrome and firefox
$ This. attr ("autocomplete", "off ");

Related Article

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.