【问题标题】:how to create search function with jquery如何用jquery创建搜索功能
【发布时间】:2015-08-21 14:24:41
【问题描述】:

我有这个 ajax 请求,它正在处理我需要的数据,但我想让它成为一个搜索功能,让用户根据请求提取数据。是否可以拿走我的工作代码并将其重新用于搜索框?不知道该怎么做...

function foodQuery(){

    var foodURL = "http://api.example.com/items?key=123456789";

    $.ajax({
        url: foodURL,
        type: 'GET',
        contentType: "text/plain",
        dataType: 'json',
        success: function(json) {

            $.each(json.products, function(index, product) { 

                // build product block
                var htmlString = '<div class="product large-3 columns">';
                //open imgwrap
                htmlString += '<div class="imgwrap">';
                //get img src
                htmlString += ' <img class="item_img" src="http://api.example.com/assets/images/' + product.itemCode + '@2x.jpg" />';
                // close imgwrap
                htmlString += '</div>';
                // open textwrap
                htmlString += '<div class="textwrap">';
                // get productName
                htmlString += '<h1 class="product_headline">' + product.productName + '</h1>' ;
                // get itemCode
                htmlString += '<h4 class="item_id" >#' + product.itemCode + '</h4>';
                // get description
                htmlString += '<p class="product_desc">' + product.description + '</p>';
                // open price
                htmlString += '<div class="price">';
                // get price & close div
                htmlString += '<span class="dollar"><span class="usd">$</span>' + product.price + '</span> <span class="product_desc">per weight</span></div>'
                // close divs
                htmlString += '</div>';

                //console.log(htmlString);
                $('.listing').append( $(htmlString) );

           }); //end each

        }, // end success
        error: function(e) {
           console.log(e.message);

           $('.listing').append( '<h1 class="errmsg" >Sorry, there was an unkown error.</h1>' );
        } // end error
    }); // end ajax request
}

【问题讨论】:

  • 为什么不在 $.each 循环中使用 'product.productName .IndexOf(smth)' >= 0 检查,如果为真,请执行您的操作,除非您告诉您的服务器进行搜索并给您确切的结果,您必须使用 O(n) 成本手动搜索它。
  • 用户会在文本框中输入什么来搜索产品?是网址中的key 吗?

标签: javascript jquery ajax json


【解决方案1】:

这取决于您使用的 API,但假设 API 可以使用文本进行搜索,您可能会得到如下所示的内容:

function foodQuery(searchTerm) {
   var foodUrl = '/path/to/api?query=' + searchTerm;

   $.ajax({
     // fill in AJAX call here and callback handling like you are doing
   }) 
}

$('#searchBox').on('keypress', function() {
  foodQuery($(this).val());
});

因此,每次用户键入时,函数foodQuery() 都会使用当前搜索词运行。您可能需要添加一些延迟,以便每次用户键入新字符时都不会触发 API。

【讨论】:

    【解决方案2】:

    首先创建一个文本输入,

    <input type="text" id="search">
    

    然后监听该输入的keyup 事件。在用户键入时获取输入值(如果这是您想要的行为)并调用foodQuery 函数将输入值作为参数发送。然后将此值用作foodURL 的key 参数。然后以与您相同的方式执行ajax 请求。

    $(function() {
    
      /** 
      Whenever user types a letter and release the key, its value is passed to the 
      foodQuery function 
      **/
      $("#search").keyup(function() {
        var value = $(this).val();
        foodQuery(value);
      });
    
      function foodQuery(key) {    // key is passed as a parameter
    
        var foodURL = "http://api.example.com/items?key=" + key;
    
        /** Send you ajax request here and manipulate the DOM the same way yo do. Since we are 
        fetching new products continuously, it is better to clear the .listing element 
        every-time before you update it. **/
    
        $(".listing").html("");
    
        /** 
        $.ajax({
            url: foodURL,
            type: 'GET',
            contentType: "text/plain",
            dataType: 'json',
            success: function(json) { **/
      }
    
    });
    

    【讨论】:

    • key 必须放在每个查询的末尾,所以像这样? $("#searchinput").keyup(function() { var value = $(this).val(); foodQuery(value); }); function foodQuery(key) { // key is passed as a parameter var foodURL = "http://api.example.com/" + value + "?key=" + key;
    • 我不明白你。您是说用户将键入的内容用作 url 中的 value 吗?在我看来,它应该只是 items 对吧?
    • 我尝试了您建议的代码,但无论我搜索什么,我每次都会收到错误消息
    猜你喜欢
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 1970-01-01
    • 2020-02-27
    相关资源
    最近更新 更多