首页 文章

使用JSON的jQuery UI自动完成

提问于
浏览
30

好吧,我的脑子就在这上面(我很可怕)但是我已经尝试过尽我所能,但仍然无法让它发挥作用 .

试图用jquery ui做自动完成

我的json看起来像这样

{"dealers":
     {
         "1156":"dealer 1",
         "1122":"dealer 2",
         "1176":"dealer 3",
         "1491":"dealer 4",
         "1463":"dealer 5",
         "269":"dealer 6"
    }
}

我试图使用此信息作为自动完成的来源 . 我得到的响应对象很好我只是遇到了正确的格式,所以我可以将“###”放在一个隐藏的字段中,该字段与“值”相关联,需要显示为“值”落下 .

一直在尝试百万种不同的方式,但最近的尝试是在下面

function ajaxCall() {
    $.getJSON("/example/location/example.json?term=" + $('#dealerName').val(),
        function(data) {
        $.each(data.dealers, function(k, v) {                
                alert(k + ' : ' + v);
        });
    });        
}

$('#dealerName').autocomplete({
    source: ajaxCall,
    minLength: 2,
    delay: 100
});

拜托,谢谢!

3 回答

  • 1

    您需要以jQueryUI期望的格式将要返回的对象转换为数组 .

    您可以使用$.mapdealers 对象转换为该数组 .

    $('#dealerName').autocomplete({
        source: function (request, response) {
            $.getJSON("/example/location/example.json?term=" + request.term, function (data) {
                response($.map(data.dealers, function (value, key) {
                    return {
                        label: value,
                        value: key
                    };
                }));
            });
        },
        minLength: 2,
        delay: 100
    });
    

    请注意,当您选择项目时,"key"将被放置在文本框中 . 您可以通过调整 $.map 的回调函数返回的 labelvalue 属性来更改此设置 .

    或者,如果您可以访问生成JSON的服务器端代码,则可以更改返回数据的方式 . 只要数据:

    • 是具有 label 属性, value 属性或两者的对象数组,或者

    • 是一个简单的字符串数组

    换句话说,如果您可以格式化数据,如下所示:

    [{ value: "1463", label: "dealer 5"}, { value: "269", label: "dealer 6" }]
    

    或这个:

    ["dealer 5", "dealer 6"]
    

    然后你的JavaScript变得更简单:

    $('#dealerName').autocomplete({
        source: "/example/location/example.json"
    });
    
  • 64

    我知道它已经得到了解答 . 但我希望这将有助于将来的某些人,并节省大量的时间和痛苦 .

    完整的代码如下:这是我为文本框做的,使其在CiviCRM中自动完成 . 希望它可以帮到某人

    CRM.$( 'input[id^=custom_78]' ).autocomplete({
                autoFill: true,
                select: function (event, ui) {
                        var label = ui.item.label;
                        var value = ui.item.value;
                        // Update subject field to add book year and book product
                        var book_year_value = CRM.$('select[id^=custom_77]  option:selected').text().replace('Book Year ','');
                        //book_year_value.replace('Book Year ','');
                        var subject_value = book_year_value + '/' + ui.item.label;
                        CRM.$('#subject').val(subject_value);
                        CRM.$( 'input[name=product_select_id]' ).val(ui.item.value);
                        CRM.$('input[id^=custom_78]').val(ui.item.label);
                        return false;
                },
                source: function(request, response) {
                    CRM.$.ajax({
                        url: productUrl,
                            data: {
                                            'subCategory' : cj('select[id^=custom_77]').val(),
                                            's': request.term,
                                        },
                        beforeSend: function( xhr ) {
                            xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
                        },
    
                        success: function(result){
                                    result = jQuery.parseJSON( result);
                                    //console.log(result);
                                    response(CRM.$.map(result, function (val,key) {
                                                             //console.log(key);
                                                             //console.log(val);
                                                             return {
                                                                     label: val,
                                                                     value: key
                                                             };
                                                     }));
                        }
                    })
                    .done(function( data ) {
                        if ( console && console.log ) {
                         // console.log( "Sample of dataas:", data.slice( 0, 100 ) );
                        }
                    });
                }
      });
    

    关于我如何在自动完成中将数据返回到此jquery ajax调用的PHP代码:

    /**
     * This class contains all product related functions that are called using AJAX (jQuery)
     */
    class CRM_Civicrmactivitiesproductlink_Page_AJAX {
      static function getProductList() {
            $name   = CRM_Utils_Array::value( 's', $_GET );
        $name   = CRM_Utils_Type::escape( $name, 'String' );
        $limit  = '10';
    
            $strSearch = "description LIKE '%$name%'";
    
            $subCategory   = CRM_Utils_Array::value( 'subCategory', $_GET );
        $subCategory   = CRM_Utils_Type::escape( $subCategory, 'String' );
    
            if (!empty($subCategory))
            {
                    $strSearch .= " AND sub_category = ".$subCategory;
            }
    
            $query = "SELECT id , description as data FROM abc_books WHERE $strSearch";
            $resultArray = array();
            $dao = CRM_Core_DAO::executeQuery( $query );
            while ( $dao->fetch( ) ) {
                $resultArray[$dao->id] = $dao->data;//creating the array to send id as key and data as value
            }
            echo json_encode($resultArray);
        CRM_Utils_System::civiExit();
      }
    }
    
  • 0

    我用这个脚本进行自动完成...

    $('#custmoers_name').autocomplete({
        source: function (request, response) {
    
            // $.getJSON("<?php echo base_url('index.php/Json_cr_operation/autosearch_custmoers');?>", function (data) {
              $.getJSON("Json_cr_operation/autosearch_custmoers?term=" + request.term, function (data) {
              console.log(data);
                response($.map(data, function (value, key) {
                    console.log(value);
                    return {
                        label: value.label,
                        value: value.value
                    };
                }));
            });
        },
        minLength: 1,
        delay: 100
    });
    

    我的json返回: - [{"label":"Mahesh Arun Wani","value":"1"}] 搜索后 m

    但它显示在下拉列表 [object object] ...

相关问题