JSONP Cross request Baidu Search API implementation drop-down list prompt

Source: Internet
Author: User
Tags script tag chrome developer

Source of the topic: 

Recently in Baidu Ife front-end Technical college, then there is a problem is the simulation of Baidu search smart tips. The topic is open source, give the address later.

Because Bo Master did not learn after the end Ah, want to cry no tears, so can not achieve back-end fuzzy search, if the front-end Ajax purely request a copy of the same data, the effect is not good.

The witty blogger directly borrowed the Baidu search API.

Monitor the network directly from the developer tools to find the requested address.

  Baidu API:

I reduced the API a bit and removed most of the parameters that were temporarily unused.

Https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/su? WD=abc&json=1&p=3&CB=aralic&t

Parameters Value
Wd Key words
Json 1
P 3
Cb callback function

parameter Description:

Here we just need to focus on two parameters, the first is the keyword to be requested, and the second is the callback function. Believe too many people know Jsonp, full name is JSON with padding. If you have unfamiliar, you can look at other Daniel's blog from the Garden to understand first.

  HTML code:

<div id= "Container" >        <input type= "text" id= "kw" >        <ol id= "dataList" >        </ol></ Div>

  JavaScript section:

Problem and feature implementations are broadly divided into six parts:

    1 . What are the conditions for requesting data or triggering the request data?

    2, How to request data?

    3, data How to format processing?

    4 . How to put the processed data into the page?

    5, to achieve the keyboard up and down buttons toggle pull-down tips

    6,Enter the button to open a new page, jump to search results

Solution:

   1, I can say against the question 1 I went to check the information?

Within the input search, keyboard events that can be added are onkeydown<onkeypress<onkeyup by time. If you do not judge the input key value code, then in order to get the value just entered in the search box, you can only use the onkeyup event, or you can not get the value just entered.

   2, the request data method, the exciting moment arrived, to paste the code.

Press the key to lift the event function GetData () {//drop-down    hint list    var odatalist = $ (' #dataList ');    Search box    var sInput = $ (' #kw ');    var oldValue = null;    The value of the current text box is not empty and is not the same as before    if (sinput.value! = "&& sinput.value! = oldValue) {        //Create script tag        var oscript = Document.createelement (' script ');        Get timestamp        var otime = new Date (). GetTime ()        oscript.src = ' https://sp0.baidu.com/5a1Fazu8AA54nxGko9WTAnF6hhy/ Su?wd= ' + (sinput.value) + ' &json=1&p=3&cb=aralic&otime ';        Document.body.appendChild (Oscript);    } else if (Sinput.value = = ") {        //If the text box value is empty clears the contents of odatalist and hides        oDataList.style.display = ' none ';        odatalist.innerhtml = "";    }     OldValue = Sinput.value;}

    3, data processing, this is the data requested by JSONP, so you need to create a new function in the global. The parameter is data (Jsonp sent);

You can find the request directly from the Chrome Developer tool, and then there's a preview on the right that previews the returned data and, of course, a simpler formatting method

Print the data directly inside the function console and read the formatted data.

       

      

A JSON data is returned, q denotes the search keyword, s is the array type, and the matching value is returned.

     4, the processing of data and added to the page.

JSONP callback function Aralic (data) {Console.log (data);    var odatalist = $ (' #dataList ');    var sInput = $ (' #kw ');    var str = ';       var inow =-1; When there is data returned if (data.s.length) {//splicing string for (var i = 0; i<data.s.length; i++) {str + = < Li><a href= "https://www.baidu.com/s?wd= ' +data.s[i]+ '" target=_blank> ' +data.s[i]+ ' </a></li> '        ;        } oDataList.style.display = ' block ';        odatalist.innerhtml = str;            ↑↓ two key Events Document.onkeydown = function (EV) {var ev = EV | | window.event;            var aLi = odatalist.getelementsbytagname (' li '); ↓ key if (Ev.keycode = =) {for (var i = 0; i<ali.length; i++) {ali[i].c                Lassname = ";                } Inow + +;                if (Inow = = ali.length) {inow = 0; }//Remove binding event to text box Removeevent (sInput, ' KeyUp ', getData);                Sinput.value = Data.s[inow];            Ali[inow].classname = "active"; } else if (Ev.keycode = =) {for (var i = 0; i<ali.length; i++) {Ali[i].classname                = ";                } Inow = iNow-1;                if (Inow = =-1) {inow = ali.length-1;                } removeevent (SInput, ' KeyUp ', getData);                Sinput.value = Data.s[inow];            Ali[inow].classname = "active"; } Document.onkeyup = function () {//rebind event addevent (sInput, ' KeyUp ',            GetData);        }}//No data returned when UL content is empty and hidden} else {oDataList.style.display = ' none ';    odatalist.innerhtml = ""; }   }

   5, the button up and down the move control drop-down hint list. There was a problem in the middle that bothered me for a long time.

At first, I give the input box a keyboard lift event, and if the value of the current input box changes, then I go to request new data.

I then implement the keyboard control drop-down hint list and update the list of selected dropdown prompts into the input box. Weird thing happened, the value of the text box changes, immediately request new data

drop-down hint list re-rendered, I go to Baidu home page to see the effect of Baidu, up and down button control update to the value of the input box will not re-request data.

After careful analysis to find out the reason, because the focus is still in the input box, and the top and bottom buttons, although the document is bound to the event, but can't cover the event capture AH. So the value of the text box has also been changed.

In view of this, I am bound to the text box key lifting event, when the trigger key up and down (onkeydown event) to move the selected drop-down prompt, move out of the text box binding event, when the mouse lifted up when I

Rebinding event, good wit has wood there!

    6 . How do I press ENTER to open the search results page?

The browser has a default behavior for hyperlinks, do not need to add a separate enter event, when the data page rendering, the address of a is assigned, the address is Https://www.baidu.com/s?wd=keyword

    Description: Limited to space, event binding, event removal code is not posted here. The People's Congress three, the experience is slightly shallow, welcome you to correct.

Attached Baidu Ife front-end Technical Institute address: HTTPS://GITHUB.COM/BAIDU-IFE/IFE/TREE/MASTER/TASK/TASK0002

Jsonp cross-request Baidu Search API implementation drop-down list hint

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.