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

Source: Internet
Author: User

Please visit and download all resources and source code http://www.cckan.net on my blog

 

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': '1324113456725' };    $.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);        }    });}

 

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"];   }

 

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 the code

The style is as follows:

View code # 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 A {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 the 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 event function Init () {$ ("# allsitesboxhdl") of the object [0]. style. display = "NONE"; $ (": Text "). each (function () {if ($ (this) [0]. getattribute ('url') = 'true') {// Add attributes to all texts $ (this ). BIND ("keyup", onkeyup); // $ (this) when the key is pressed ). BIND ("mousedown", boxshowurls); // $ (this) when the mouse is down ). BIND ("mouseout", boxhide); // $ (this) when the mouse leaves ). BIND ("Paste", onpaste); // process HTTP; // $ (this) [0]. setattribute ("AutoComplete", "off") ;}}) ;}copy the 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)

View code // ----------------------------------------- implement the method of inputting multiple input boxes simultaneously. // obtain the control idfunction 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 of 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 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; '> no record </LI> ";} if ($. trim (HTML) = "") {html = "<li style = 'font-size: 12px; '> no record </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 urlfunction 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 the function addinput (ID) {var OBJ = GETID (ID ); // if it is an input without true, 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 () ;}// registers the object's event function Init () {$ ("# allsitesboxhdl") [0]. style. display = "NONE"; $ (": Text "). each (function () {if ($ (this) [0]. getattribute ('url') = 'true') {// Add effects to the text of all URLs = true attributes $ (this ). BIND ("keyup", onkeyup); // $ (this) when the key is pressed ). BIND ("mousedown", boxshowurls); // $ (this) when the mouse is down ). BIND ("mouseout", boxhide); // $ (this) when the mouse leaves ). BIND ("Paste", onpaste); // process HTTP; // $ (this) [0]. setattribute ("AutoComplete", "off") ;}}) ;}copy the code

The webpage code is as follows:

View Code <% @ 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"> 

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://download.csdn.net/detail/sufei1013/3949230

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

--------------------------------------------------------------- Signature section --------------------------------------------------------------

You are welcome to repost the article. If you have reposted the article, please indicate that the article is from:
Http://sufei.cnblogs.com/

Signature: Make a proud career in one's life; repay those who have helped me in the lifetime; and be able to help those who need help;


------------------------------------------------------------- Recommended articles --------------------------------------------------------

  • Previous: Collection of common website design skills
  • Next article: Recently, QQ, a netizen, contacted me to solve the problem.
  • Top
    3
    Step on
    0

    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.