Using JSONP Cross-domain call Baidu JS Implementation of the search box intelligent tips _javascript Tips

Source: Internet
Author: User
Tags custom name

Search is often used in projects, especially the Web site of navigation classes. Do your own keyword search is not realistic, direct call Baidu is the best choice.
The use of Jquery.ajax Jsonp method can be called to the exotic Baidu JS and get the return value, of course, $.getscript can also be implemented across domain calls JS.

OK, understand the principle and application of JSONP, we look at Baidu's smart tips is how to do
Look at the request from Baidu search under the Chrome Debugging window. When the keyword "A" is entered, the request is as follows:

Use Firebug to look at the requested parameters, as shown in the figure:

Request mode:GET request
Request Parameters:WD is obviously the keyword to search; CB is a request to return the processing function, the name can be casually given; T is a timestamp, to prevent caching; p do not know what meaning, each request to give 3 on it; SID doesn't know what it means, you can ask for it, and you can bring it if you want. , the value is the value of the screenshot above.

Request the address and parameters are known, so write the following JS test whether you can get keyword tips (source code in the test.html page):

var qsdata = {' WD ': ' A ', ' P ': ' 3 ', ' CB ': ' GetData ', ' t ': New Date (). Getmilliseconds (). toString ()};
  $.ajax ({
   async:false,
   URL: "Http://suggestion.baidu.com/su",
   type: "Get",
   dataType: ' Jsonp ',
   JSONP: ' Jsoncallback ',
   data:qsdata,
   timeout:5000,
   success:function (JSON) {
   },
   error: function (XHR) {
   }
 });

Qsdata encapsulates all the parameters that are requested to be sent; GetData is a custom name for processing the returned keyword (the following sample code prints the requested keyword back to the Firebug console):

 function GetData (data) {
   var Info = data[' s '];//Get Asynchronous Data
   Console.log (Info);
  } 

Monitor the text box, send the AJAX request in real time and get the data back:

OK, the test is available and you can actually get a keyword hint. But always can not put a bunch of keywords to the front desk to let users see, at least, like Baidu, you can use the mouse and keyboard direction key from the candidate Word box selection.
The most important thing to do, now start to write a complete smart hint and match the mouse and keyboard to the candidate Word operation (index.html page in the source code), to achieve the following functions:
1. Instant Monitor letter key and number key, press on to send Ajax request (also can set delay send request, source code has); At the same time monitor space, backspace, Delete, enter key;
2. Mouse to move into the pop-up layer highlighted selected line, click on the screen;
3. Press the keyboard up and down direction key can choose the candidate words, carriage return submits jumps to the Baidu search page;
4. Click on the other parts of the page to automatically hide pop-up box;
5. Press the ESC key to hide the pop-up box

Monitor the mouse and keyboard input JS (autocomplete.js source code has more detailed comments):

var Timeoutid; Deferred request server var highlightindex =-1;
  Highlight $ (function () {$ ("#searchText"). KeyUp (function (event) {var MyEvent = event | | window.event;
  var keycode = Myevent.keycode;

  Console.log (KeyCode);  Monitor keyboard if (keycode >= && keycode <= | | keycode >=-&& keycode <= | | keycode >= && keycode <= 111 | | KeyCode >= 186 && keycode <= 222 | | KeyCode = 8 | | keycode = 46 | | KeyCode = 32 | |
   KeyCode = = 13) {//Delay operation//cleartimeout (Timeoutid);
   Timeoutid = settimeout (function () {//Timeoutid = Fillurls (); } fillurls ();
   The asynchronous request if (Highlightindex!=-1) {highlightindex =-1; "Else If" (KeyCode = | | keycode = =) {if (KeyCode = 38) {//up var autonodes = $ ("#auto"). Children ("
     Div ") if (Highlightindex!=-1) {Autonodes.eq (highlightindex). CSS (" Background-color "," white ");
    highlightindex--; else {Highlightindex = Autonodes. length-1;
    } if (Highlightindex = = 1) {highlightindex = autonodes.length-1;
    } autonodes.eq (Highlightindex). CSS ("Background-color", "#ebebeb");
    var comtext = Autonodes.eq (highlightindex). text ();
   $ ("#searchText"). Val (Comtext); } if (keycode = = 40) {//down var autonodes = $ ("#auto"). Children ("div") if (Highlightindex!=-1) {Autonod
    Es.eq (Highlightindex). CSS ("Background-color", "white");
    } highlightindex++;
    if (Highlightindex = = autonodes.length) {highlightindex = 0;
    } autonodes.eq (Highlightindex). CSS ("Background-color", "#ebebeb");
    var comtext = Autonodes.eq (highlightindex). text ();
   $ ("#searchText"). Val (Comtext); } else if (keycode = 13) {//Carriage return if (Highlightindex!=-1) {var Comtext = $ ("#auto"). Hide (). Children ("div"). E
    Q (highlightindex). text ();
    Highlightindex =-1;
   $ ("#searchText"). Val (Comtext);
    else {$ (' #auto '). Hide ();
   $ ("#searchText"). Get (0). blur (); } else if (keycode = = 27) {//press ESC to hide the pop-up layer if ($ ("#auto"). Is (": visible")) {$ ("#auto"). Hide ();

 }
  }
 });

Finally realize the effect display. Mouse can choose the candidate words can also be keyboard key choice, click on the screen, enter the direct jump to Baidu page:

SOURCE Download: Http://xiazai.jb51.net/201608/yuanma/baidusearch (jb51.net). rar

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.