如何将jQuery UI自动完成功能修改为适合Python

1 投票
2 回答
593 浏览
提问于 2025-04-16 13:18

在这个例子中,不用search.php,我该怎么用Python的方法来返回数据呢?比如说,这样写可以吗:$.getJSON("{{ data }}", { term: extractLast(request.term) }, response );

       $(function() {
    function split( val ) {
        return val.split( /,\s*/ );
    }
    function extractLast( term ) {
        return split( term ).pop();
    }

    $( "#birds" )
        // don't navigate away from the field on tab when selecting an item
        .bind( "keydown", function( event ) {
            if ( event.keyCode === $.ui.keyCode.TAB &&
                    $( this ).data( "autocomplete" ).menu.active ) {
                event.preventDefault();
            }
        })
        .autocomplete({
            source: function( request, response ) {
                $.getJSON( "search.php", {
                    term: extractLast( request.term )
                }, response );
            },
            search: function() {
                // custom minLength
                var term = extractLast( this.value );
                if ( term.length < 2 ) {
                    return false;
                }
            },
            focus: function() {
                // prevent value inserted on focus
                return false;
            },
            select: function( event, ui ) {
                var terms = split( this.value );
                // remove the current input
                terms.pop();
                // add the selected item
                terms.push( ui.item.value );
                // add placeholder to get the comma-and-space at the end
                terms.push( "" );
                this.value = terms.join( ", " );
                return false;
            }
        });
});

2 个回答

0

你需要让你的Python脚本输出一个格式化为JSON的字符串,这个字符串里包含一个数据数组。我敢打赌,Python有一个库可以帮助你把对象、数组、字符串等转换成JSON格式的字符串。只要把合适的数组转换成JSON字符串,你的JavaScript就能加载它。不过,从这个例子中,我无法告诉你具体应该返回什么。

祝你好运!

0

我使用的是simplejson这个包。你没有说明你想用哪个Python框架。像这样的写法是很常见的:

json = simplejson.dumps(obj)
return HttpResponse(json, "application/json")

如果你想看更完整的实现,可以看看我的 json.py模块

撰写回答