Using JSONP to implement search box function in jquery _jquery

Source: Internet
Author: User

Previous words:
I was hoping to send a copy of Bing search last week. But before I was ready to write an article, I suddenly thought of learning Ajax technology, where I also had a page where I could get data without having to manually refresh it. But I found that using the previous method did not get the effect I wanted. But a few days ago the computer to change the system, the previous source code lost (the front has a bad habit is to put the latest in doing things on the desktop). Today I want to get to the point completely.

Try a preliminary attempt with jquery and Ajax:

(This code is a reference to the Web, search box production video production, for specific details please refer to the video.) My previous code could not be found, the first idea is also from there, so this time directly using the code there

HTML code:

 <div class= "Bg-div" > 
  <div class= "Search-box" > 
   <div class= "logo" ></div> 
   < Form id= "Search-form" > 
    <input type= "text" class= "Search-input-text" autocomplete= "Off" name= "Q" id= "search _input "/> 
    <input type=" Submit "class=" Search-input-button "value=" "id=" Search_submit "> 
   </form > 
  </div> 
 </div> 
  
 <div class= "suggest" id= "Search-suggest" <!--style= "Display:none ;" -->> 
  <ul id= "Search-result" > 
   <li> search results 1</li> 
   <li> Search Results 2</li> 
  </ul> 
 </div> 

CSS code:

* {padding:0; 
margin:0; 
 } body {}. bg-div{background-image:url (' images/river.jpg '); 
 width:1228px; 
 height:690px; 
 margin:0 Auto; 
position:relative; 
 }. Logo {background-image:url (' images/logo.png '); 
 width:107px; 
 height:53px; 
 Float:left; 
Margin: -4px 18px 0 0; 
 form {float:left; 
 Background-color: #fff; 
padding:5px; 
 }. search-input-text {border:0; 
 Float:left; 
 height:25px; 
 line-height:25px; 
 Outline:none; 
 width:350px; 
font-size:16px; 
 }. Search-input-button {border:0; 
 Background-image:url (' images/search-button.png '); 
 width:29px; 
 height:29px; 
Float:left; 
 }. search-box {position:absolute; 
 top:200px; 
left:300px; 
 } #search-suggest {width:388px; 
 Background-color: #fff; 
 border:1px solid #999; 
Display:none; 
}. Suggest ul {list-style:none; 
 }. Suggest ul li {padding:3px; 
 font-size:14px; 
 line-height:25px; cursor:pointer;/* Hand///* This code toDrop Position:absolute;
 Left:----px;
  Top:----px; 
 */}. Suggest ul li:hover {text-decoration:underline; 
Background-color: #e5e5e5; 
 }

Use jquery to achieve results:
before that, we basically got the graphic effect we wanted, but when we entered what we wanted in the search box it was not going to work at this time (the General search box effect is in the keyboard input, the following will show a part associated with the key search information, Then click on the mouse to move up and then jump to the corresponding link. For step-by-step verification of our ideas, we modify the previous code here.

1, the positioning of the Li tag removed;

2. In HTML, set the LI tag to hide. Then we'll do the following.

think about one: how to display the relevant information when the keyboard is entered (that is, the contents of the Li tag)?

Idea: We first introduce jquery, then execute a keyboard event after the document is loaded, and then change the CSS effect in the keyboard event

$ (function () {
 //keyboard event
 $ ("#search_input"). Bind ("KeyUp", function () {
    $ ("#search-suggest"). Show (). CSS ({ Top
     : $ ("#search-form"). Offset (). Top + $ ("#search-form"). Height () +10, left
     : $ ("#search-form"). Offset (). Left,
     position: "Absolute",
    });
 });

At this time, when we enter content in the search box, the following will display the corresponding search (simulation)

thinking about the second: how to implement the mouse click on the Search button, will search the corresponding content?

Train of thought: Click the event with the mouse, let the mouse click to set an address, click to jump directly to the corresponding address, code to achieve:

 Event Agent--Mouse click event
 $ (document). Delegate ("Li", "click", Function () {
  var keyword = $ (this). text ();
  Location.href = "http://cn.bing.com/search?q=" + keyword;
 });

thinking Three: How do we enter data in the search box, the following will prompt the relevant search information?
Idea: We use the get in jquery to implement, reference code:

  var SearchText = $ ("#search_input"). Val ();
  $.get ("http://api.bing.com/qsonhs.aspx?q=" +searchtext, function (data) {
    console.log (data);
    var d = data.as. Results[0]. suggests;
    var html = "";
    for (var i = 0; i < d.length i++) {
     html = "<li>" +d[i]. txt+ "</li>";
    }
    $ ("#search-result"). HTML (HTML);
   }
   , "JSON");

Here, we should be able to get the results we want, but, for a long time did not find where the wrong. The video goes on to describe the cross-domain operation with JSONP, but I also follow the action in the video and never get the results I want, so I dive into the JavaScript Advanced program to find out about the usage of JSONP.

About JSONP:
about Jsonp, "JavaScript Advanced Program Design," a book introduced less, below is what I read after the induction.
Jsonp's full write is JSON with padding, which appears to solve the problem of the homologous policy between the main browsers, in general, the page below ServerA domain is not able to communicate with the resources below ServerA, while the Html <script > element is an exception, using <script> this open source strategy, the Web page can dynamically obtain JSON data from other sources, and this pattern is called JSONP, with JSONP capture is not really the meaning of json but arbitrary JavaScript, it is straight Is compiled from the JavaScript compiler instead of the JSON interpreter. For more information on JSON please click:http://www.cnblogs.com/foodoir/p/5894760.html View

Since the book is not written, then go to the Internet to search for resources. Here's a piece of code that intercepts the information about the front of the article:

  $.ajax ({
    type: "Get",
    async:false,
    URL: "http://flightQuery.com/jsonp/flightResult.aspx?code=CA1998" ,
    dataType: "Jsonp",
    Jsonp: "Callback",//passed to the request handler or page to obtain the parameter name of the JSONP callback function name (general default: callback)    
    Jsonpcallback: "Flighthandler",//Custom JSONP callback function name, default to jquery automatically generated random function name, also can write "?", jquery will automatically process data for you   
success: function (JSON) {
     alert (json.price + json.tickets + ' Zhang.) ');
    },
    error:function () {
     alert (' fail ');
    }
   );

Use this code to modify our own code:

  $.ajax ({
   type: "Get",
   URL: "http://api.bing.com/qsonhs.aspx?type=cb&q=" + SearchText,
   dataType: " Jsonp ",
   jsonp: ' CB ',
   success:function (data) {
    var d = data.as. Results[0]. suggests;
    var html = "";

    for (var i = 0; i < d.length i++) {

     html = "<li>" + d[i]. TXT + "</li>";
    }
    $ ("#search-result"). HTML (HTML);

    $ ("#search-suggest"). Show (). CSS ({top
     : $ ("#search-form"). Offset (). Top + $ ("#search-form"). Height () + Ten,
     Left: $ ("#search-form"). Offset (). Left,
     position: "Absolute",
    });
   }
   

more thinking: We can add some judgment in front, let our effect achieve more perfect

 if (data = = NULL) {
     $ ("#search-suggest"). Hide ();
     return false;
    }
    if (data.as = = null) {
     $ ("#search-suggest"). Hide ();
     return false;
    }
    if (data.as. Results = = null) {
     $ ("#search-suggest"). Hide ();
     return false;
    }
    if (data.as. RESULTS[0] = = null) {
     $ ("#search-suggest"). Hide ();
     return false;
    }
    if (data.as. Results[0]. suggests = = null) {
     $ ("#search-suggest"). Hide ();
     return false;
    } 

After testing the previous code, found that there is not enough to further modify the code:

 $ ("#search-form"). Submit (function () {
  var keyword = $ ("#search_input"). Val ();
  Console.log ("word=" + keyword);
  if (keyword = = null) {return false;} 
  Location.href = "http://cn.bing.com/search?q=" + keyword;
 });

Here, our effect is almost out, the effect of screenshots:

Source code is hosted to: Http://sandbox.runjs.cn/show/gfdpkysk, click to view.

After the words:

These days to learn a lot of new things, now have an idea is to put it in tandem with the recent study, do a comprehensive effect. Refer to Bing website, there are really a lot of things can be done, the next period of time to do a good job of their own to achieve better results.

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.