简体   繁体   中英

jquery-ui autocomplete does not display utf-8 correct

I have run into some problems with displaying data in jquery ui autocomplete, when i display the text, it is not utf-8 encoded, despite my db and page are using utf-8.

Also when i try to display it any other way, it show normally with the right encoding.

The jquery ui script.

<script type="text/javascript" charset="utf-8">
$(function() {
    function log( message ) {
        $( "<div>" ).text( message ).prependTo( "#log" );
        $( "#log" ).scrollTop( 0 );
    }

    $( "#items" ).autocomplete({
        source: "getSurgestedItems.php",
        minLength: 2,
        select: function( event, ui ) {
            log( ui.item ?
                "Selected: " + ui.item.value + " aka " + ui.item.id :
                "Nothing selected, input was " + this.value );
        }
    }).data("autocomplete")._renderItem = function(ul, item){
        return $("<li>")
            .data("item.autocomplete", item)
            .append("<a>" + item.value + "<br>" + item.desc + "</a>")
            .appendTo(ul);
    };
});
</script>

The php script getting the items.

while ($row = $result->fetch_assoc()) {
$i++;
if(!$first){
    $json .=',';
}
else{
    $first = false;
}

$name = addslashes($row['name']);
$desc = mb_substr(addslashes($row['description']), 0, 60, 'UTF-8');

$desc .= '...';

$json .='{"value" : "'.$name.'",
        "desc" : "'.$desc.'"}';
}
$json .=']';

echo $json;

Now like i said I have tried to displaying the data, in every way i can think of and it is only with the autocomplete feature it is displayed wrong.

SaschaM78 comment got me looking in the right direction, while looking into json_encode, I discovered that it would only work with utf-8, which led me to try and encode each string to utf-8, using mb_convert_encoding , which have solve my problem, it works fine now.

The new php code.

$json = array();

while ($row = $result->fetch_assoc()) {

$name = mb_convert_encoding($row['name'], 'UTF-8');
$desc = mb_convert_encoding(substr($row['description'], 0, 60), 'UTF-8');

$desc .= '...';

$json[] = array('value' => $name, 'desc' => $desc); 
}

echo json_encode($json);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM