Using jsonp to call Baidu js across domains to implement smart prompts in the search box, jsonpjs

Source: Internet
Author: User
Tags custom name

Using jsonp to call Baidu js across domains to implement smart prompts in the search box, jsonpjs

Search is often used in projects, especially for navigation websites. It is unrealistic to search keywords by yourself. Directly calling Baidu is the best choice.
The jsonp method of jquery. ajax can be used to call Baidu's js and obtain the return value. Of course, $. getScript can also call js across domains.

OK. After learning about the principles and applications of jsonp, let's take a look at how Baidu's Smart Tips are made.
In the chrome debugging window, check the request sent by Baidu search. When the keyword "a" is entered, the request

Use firebug to view the request parameters,

Request Method:Get request
Request Parameters:Wd is obviously the keyword to be searched; cb is the processing function returned by the request, and the name can be given at will; t is the timestamp to prevent caching; p doesn't know what it means, each request can be sent to 3. sid does not know what it means, and can be requested either. If you want it, you can include it. The value is the above value.

Both the request address and response are notified. Therefore, the following figure shows how to get the key word prompt (the test.html page in the source code) from the JS test handler ):

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 the parameters to be sent for all requests. getData is a custom name used to process the returned keywords (the following sample code prints the keywords returned by the request to the FireBug console ):

Function getData (data) {var Info = data ['s ']; // obtain asynchronous data console. log (Info );}

In the monitored text box, real-time ajax requests are sent and data is retrieved as follows:

OK. The test is available. You can get the keyword prompt. However, you cannot put a bunch of keywords on the front-end for users to see, at least like Baidu. You can use the mouse and keyboard arrow keys to select words from the candidate word box.
The most important thing is to start a new smart prompt and use the mouse and keyboard to operate the corresponding words (the index.html page in the source code) to implement the following functions:
1. Monitor the letter key and number key in real time, and press it to send ajax requests (you can also set the delay sending request, which is included in the source code). Also, monitor keys such as spaces, backspace, Delete, and Enter;
2. move the cursor to the highlighted row in the pop-up layer, and click it to bring it to the screen;
3. Press the keyboard's up and down arrow keys to select candidate words, and press enter to submit to jump to the baidu search page;
4. Click other parts of the page to automatically hide the pop-up box;
5. Press ESC to hide the dialog box

Monitor mouse and keyboard input js (autoComplete. js source code contains more detailed notes ):

Var timeoutId; // latency request server var highlightindex =-1; // highlight $ (function () {$ ("# searchText "). keyup (function (event) {var myEvent = event | window. event; var keyCode = myEvent. keyCode; // console. log (keyCode ); // monitoring keyboard if (keyCode >=65 & keyCode <= 90 | keyCode >=48 & keyCode <= 57 | keyCode >=96 & keyCode <= 111 | keyCode> = 186 & keyCode <= 222 | keyCode = 8 | keyCode = 46 | keyCode = 32 | KeyCode = 13) {// delayed operation // clearTimeout (timeoutId); // timeoutId = setTimeout (function () {// timeoutId = FillUrls (); //}, 500) FillUrls (); // asynchronous request if (highlightindex! =-1) {highlightindex =-1 ;}} else if (keyCode = 38 | keyCode = 40) {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) {// downward var autoNodes = $ ("# Auto"). children ("div") if (highlightindex! =-1) {autoNodes.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) {// press enter if (highlightindex! =-1) {var comText = $ ("# auto "). hide (). children ("div "). eq (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, the effect is displayed. You can select either a candidate word or a keyboard direction key. Click it to go to the screen and press enter to directly jump to the Baidu page:

Source code download: http://xiazai.jb51.net/201608/yuanma/baidusearch (jb51.netw..rar

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.