jQuery UI自动完成不会显示返回的json (PHP)


jQuery UI autocomplete wont display returned json (PHP)

jQuery:

$("[type=text]").autocomplete({
source: "json.php",
minLength: 0
}).addClass("ui-widget ui-widget-content ui-corner-left");

工作良好,如果我改变源:一个JS数组。我知道php正在工作,因为我可以在控制台中看到它,但这里是php示例:

$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);

所以下拉菜单没有显示。我现在感觉很傻。

在json.php文件中,确保在echo之前通过header()函数将内容编码设置为json。通过这种方式,jQuery应该将数组视为正确的json。

header("Content-Type: application/json");
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);

几天前,我也遇到了json填充自动完成的问题。

我的问题是我没有设置内容类型,正如Wally上面说的:

header("Content-Type: application/json");

我还将jQuery自动完成调用包装在getJSON中,然后使用该函数的数据填充自动完成字段。我的直觉告诉我,额外的getJSON不应该是必要的,但像你一样,我在引用我的PHP文件作为源时有问题。

$.getJSON("json.php", function(data) {
    $("[type=text]").autocomplete({
        dataType: "json",
        source: data,
        minLength: 1,
    }); 
});

由于我使用的是旧的PHP版本,所以我手工制作了JSON。我包括"label"answers"value"字段,因为我相当确定它们是自动完成工作所必需的。

$jsonList = "[{"label" : "Item 1", "value" : "1"}, {"label" : "Item 2", "value" : "2"}]";
return $jsonList;

http://jqueryui.com/demos/autocomplete/remote-jsonp.html

从演示站点查看。

$( "#city" ).autocomplete({
            source: function( request, response ) {
                $.ajax({
                    url: "http://ws.geonames.org/searchJSON",
                    dataType: "jsonp",
                    data: {
                        featureClass: "P",
                        style: "full",
                        maxRows: 12,
                        name_startsWith: request.term
                    },
                    success: function( data ) {
                        response( $.map( data.geonames, function( item ) {
                            return {
                                label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName,
                                value: item.name
                            }
                        }));
                    }
                });
            },
            minLength: 2,
            select: function( event, ui ) {
                log( ui.item ?
                    "Selected: " + ui.item.label :
                    "Nothing selected, input was " + this.value);
            },
            open: function() {
                $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
            },
            close: function() {
                $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
            }
        });