How to introduce Baidu search into your website JS implementation (with source code)

Source: Internet
Author: User

Everyone has seen this effect.

 

How can I introduce him to my website? Let's analyze it together.

You can easily obtain the keyword by using the "development tool" of Ie9. when you enter a keyword, how to obtain the smart prompt is related to the keyword.

Let's take a look.

 

We can clearly see that every time we modify the query box, Baidu sends an Ajax request to call the corresponding data.

The address is: http://suggestion.baidu.com/su? Wd = Blog & p = 3 & cb = window. bdsug. sug & t = 1324271669786

As you can see, the blog "wd = blog" is the keyword I entered. If you want to use other keywords, you only need to modify the value of wd too much.

At this time, everyone will think like this: do we only need to send a Get request, as long as an Ajax request is dynamically sent every time we query on our own website to access this address? Yes,

But do not use Http requests because these requests are initiated from your server. Of course, Baidu will certainly block you.

What should we do to avoid this problem?

There is only one method. Js is used to execute the request on the client. Because Javascript is initiated on the client, even if it is Baidu mail, it mails all users who use your website too much. I believe Baidu will not be stupid at this point. As a result, they lose many users.

So this method should be true.

But we all know that JavaScript cannot be accessed across spans, and Baidu cannot give you interfaces or permissions that span. What should we do?

Simple: we have seen above that Baidu gives us a Jsonp data format, so we can directly use the Jsonp method to initiate Ajax requests, because JS that returns Jsop format data can be accessed across Spans

Let's take a look at my code.

Function FillUrls () {var strdomin = $. trim ($ ("# Text1 "). val (); var qsData = {'wd ': strdomin, 'P': '3', 'cb': 'showdiv ', 't': '123 '}; $. 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) {alert (xhr );}});}
Copy code
The code is very simple. You should understand it at first glance. I just want to explain this sentence.

Var qsData = {'wd ': strdomin, 'P': '3', 'cb': 'showdiv ', 't': '123 '};

Wd is the keyword we want to enter.

P and don't worry.

What is cb? It is a method that is directly called when Ajax is returned. Baidu will execute the method to call the data returned. We do not need to do any processing.

You only need to write a method to accept the data.

Function ShowDiv (strurls) {var urls = strurls ["s"];}
Copy code
Urls is the data we need. Let's take a look at the data style returned after the call.

ShowDiv ({q: "blog", p: false, s: ["blog China", "blog Garden", "blog bus", "blog network", "blog login ", "blog registration", "blog search", "blog posting", "blog Sina", "blog posting master"]});
Copy code
This is the data returned by Baidu. We only need the data after s. Now we should understand the meaning of writing var urls = strurls ["s.

You can try it on your own.

Because Baidu only returns data, we need to create a box for providing intelligence, which can be defined by ourselves. Let's take a look at this box.

<Div style = "display: none; position: absolute;" id = "allSitesBoxHdl" class = "classlist" onmouseover = "this. style. display = 'block' "onmouseout =" this. style. display = 'none' "> <ul id =" allSitesBoxContent "> </ul> </div>
Copy code
The style is as follows:

# AllSitesBoxHdl. classlist
{
Position: absolute;
Background-color: # F5FBFF;
Width: 256px;
Border: 1px solid # C9E4F4;
Top: 28px;
Left: 0;
Text-align: left;
Font-size: 14px;
Line-height: 30px;
Padding: 1px;
}
# AllSitesBoxHdl. classlist li
{
Display: inline;
}
# AllSitesBoxHdl. classlist li. lis
{
Text-decoration: none;
Height: 30px;
Width: 210px;
Float: left;
Padding-left: 8px;
Color: #666;
}
# AllSitesBoxHdl. classlist li. lis a: hover
{
Color: #016493;
Background-color: # edf6fb;
}
# AllSitesBoxHdl. classlist li. lis a: active
{
Color: #016493;
Background-color: # edf6fb;
}
# AllSitesBoxHdl. classlist li. lis input
{
Cursor: pointer;
Color: # FF6600;
Border-right: 1px solid # ccc;
Border-bottom: 1px solid # ccc;
Height: 22px;
Margin: 4px;
Line-height: 22px;
Float: right;
Background: # fff;
}
. Wena
{
Color: #666;
Font-size: 12px;
Height: 30px;
Line-height: 30px;
Width: 250px;
Float: left;
}
Copy code

 

In the first step, we need to register an event to bind some effect events of the control, which can be achieved only when data is input.

The method is as follows:


// Register the object event
Function Init (){
$ ("# AllSitesBoxHdl") [0]. style. display = "none ";
$ (": Text"). each (function (){
If ($ (this) [0]. getAttribute ('url') = 'true') {// Add attributes to all text
$ (This). bind ("keyup", OnKeyup); // when you press the button
$ (This). bind ("mousedown", BoxShowUrls); // when the mouse is down
$ (This). bind ("mouseout", BoxHide); // when the mouse leaves
$ (This). bind ("paste", OnPaste); // process http ;//
$ (This) [0]. setAttribute ("autocomplete", "off ");
}
});
}
Copy code

 

In this method, if ($ (this) [0]. getAttribute ('url') = 'true') {// Add an effect to the Text of all url = true attributes

It means that all the Text boxes that reference this webpage can achieve this effect if there is a property of url = 'true'. That is to say, we only need to introduce the style and Js file, then add an attribute directly for the control to display.

Url = 'true' is enough, and nothing else needs to be done. Is it very convenient.

Let's take a look at the implementation of the binding method.

Below is the entire Js file (this also includes the effect of inputting multiple text boxes at the same time)

 

// ----------------------------------------- Method for inputting multiple input boxes simultaneously -----------------------------------------------

// Obtain the Control ID.

Function getid (id ){

Return (typeof id = 'string ')? Document. getElementById (id): id

};

Function getOffsetTop (el, p ){

Var _ t = el. offsetTop;

While (el = el. offsetParent ){

If (el = p) break;

_ T + = el. offsetTop

}

Return _ t

};

Function getOffsetLeft (el, p ){

Var _ l = el. offsetLeft;

While (el = el. offsetParent ){

If (el = p) break;

_ L + = el. offsetLeft

}

Return _ l

};

 

Var currentInput = null;

// Modify the attribute display list

Function BoxShow (e ){

Var input = e;

If (! Input. id ){

Input = e.tar get? E.tar get: e. srcElement;

}

CurrentInput = input;

FillUrls ();

Var box = getid ("allSitesBoxHdl ");

If (box. style. display = 'block' & currentInput. id = input. id ){

Return;

}

Box. style. left = (getOffsetLeft (input) + 'px ';

Box. style. top = (getOffsetTop (input) + (input. offsetHeight-1) + 'px ';

Box. style. width = (input. offsetWidth-4) + 'px ';

Box. style. display = 'block ';

}

// Display the list

Function BoxShowUrls (e ){

Var input = e;

If (! Input. id ){

Input = e.tar get? E.tar get: e. srcElement;

}

BoxShow (e );

}

// Set the value for Input

Function InputSetValue (val ){

Var obj = currentInput;

Obj. value = val;

If (obj. getAttribute ('url') = 'true '){

Var tags = document. getElementsByTagName ('input ');

For (var I = 0; I <tags. length; I ++ ){

If (tags [I]. getAttribute ('url') = 'true' & tags [I]! = Obj ){

Tags [I]. value = val;

}

}

}

BoxHide ();

}

 

Function BoxHide (){

If (getid ("allSitesBoxHdl ")){

Getid ("allSitesBoxHdl"). style. display = 'none ';

}

}

// Load the list

Function FillUrls (){

Var strdomin = $. trim ($ ("# Text1"). val ());

Var qsData = {'wd ': strdomin, 'P': '3', 'cb': 'showdiv ', 't': '123 '};

$. 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 ){

Alert (xhr );

}

});

}

Function ShowDiv (strurls ){

Var urls = strurls ["s"];

Var html = "";

If (urls ){

Var urllist = urls;

Var forlength = 0;

Var stringcookie;

For (var I = urllist. length-1; I> = 0; I --){

Var textval = urllist [I];

If ($. trim (textval )! = "" & $. Trim (textval )! = "Undefined "){

Html + = "<li class = \" lis \ "> <a href = \" javascript: InputSetValue ('"+ textval + "'); \ ">" + textval + "</a> </li> <br/> ";

}

}

} Else {

Html = "<li style = 'font-size: 12px; '> & nbsp; no records </li> ";

}

If ($. trim (html) = ""){

Html = "<li style = 'font-size: 12px; '> & nbsp; no records </li> ";

}

Getid ("allSitesBoxContent"). innerHTML = html;

}

// Disable the Input Method

Function closeIME (e ){

Var obj = e.tar get? E.tar get: e. srcElement;

Obj. style. imeMode = 'Disabled ';

}

 

Function OnPaste (e ){

Var obj = e.tar get? E.tar get: e. srcElement;

SetTimeout ("MoveHttp ('" + obj. id + "')", 100 );

}

// Modify the URL

Function MoveHttp (id ){

Var val = getid (id). value;

Val = val. replace ("http ://","");

If (val [val. length-1] = '/'){

Val = val. substring (0, val. length-1 );

}

Getid (id). value = val;

}

Function OnKeyup (e ){

Var obj = e.tar get? E.tar get: e. srcElement;

SetTimeout ("addInput ('" + obj. id + "')", 200 );

}

// Assign a value

Function addInput (id ){

Var obj = getid (id );

// If it is an input without True, it is not executed.

If (obj. getAttribute ('url') = 'true '){

If (obj. value. indexOf ('. ')> 0 ){

Obj. value = obj. value. replace ('. ','.');

}

Var tags = document. getElementsByTagName ('input ');

For (var I = 0; I <tags. length; I ++ ){

If (tags [I]. getAttribute ('url') = 'true' & tags [I]! = Obj ){

Tags [I]. value = obj. value;

}

}

}

FillUrls ();

}

// Register the object event

Function Init (){

$ ("# AllSitesBoxHdl") [0]. style. display = "none ";

$ (": Text"). each (function (){

If ($ (this) [0]. getAttribute ('url') = 'true') {// Add effects to the Text of all url = true attributes

$ (This). bind ("keyup", OnKeyup); // when you press the button

$ (This). bind ("mousedown", BoxShowUrls); // when the mouse is down

$ (This). bind ("mouseout", BoxHide); // when the mouse leaves

$ (This). bind ("paste", OnPaste); // process http ;//

$ (This) [0]. setAttribute ("autocomplete", "off ");

}

});

}


The webpage code is as follows:

<% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "Default. aspx. cs" Inherits = "_ Default" %>

<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> </title>
<Link href = "Scripts/StyleSheet.css" rel = "stylesheet" type = "text/css"/>
<Script src = "Scripts/jquery-1.4.1.min.js" type = "text/javascript"> </script>
<Script src = "Scripts/JScript2.js" type = "text/javascript"> </script>
</Head>
<Body>
<Form style = "text-align: center" id = "form1" runat = "server">
<Br/>
<Input style = "width: 500px;" url = "true" id = "Text1" type = "text"/> <br/>
<Input style = "width: 500px;" id = "Text2" type = "text"/>
<Div style = "display: none; position: absolute;" id = "allSitesBoxHdl" class = "classlist"
Onmouseover = "this. style. display = 'block'" onmouseout = "this. style. display = 'none'">
<Ul id = "allSitesBoxContent">
</Ul>
</Div>
<Script type = "text/javascript"> Init (); </script>
</Form>
</Body>
</Html>
Copy code

 

Let's take a look at the effect.

Isn't it a breeze.

It is not just Baidu, But Soso and Sogou can all be implemented in the same way.

If you are interested, you can download this example. : Http://files.cnblogs.com/sufei/baiduList.zip

If it feels good, recommend it to your younger brother.

 

From sufei-Perky Su
 

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.