将DBF中的UTF-8编码JSON解析为JS

时间:2014-05-15 01:00:45

标签: javascript php json encoding utf-8

我的数据库中有以下列,使用UTF-8编码的字母:

  • chineseWords

    nǐhǎo

console.log(value)给出:null


如果我将它们更改为非UTF-8,

  • chineseWords

    ni hao

console.log(value)给出:ni hao


如果我只保留一个字

  • chineseWords

console.log(value)给出:n?


jQuery的:

function getData (functionToRun) {  
    $.getJSON("phpscripts.php", {"_functionToRun" : functionToRun},
        function (returned_data) {                      
            var value = returned_data.chineseWords;         
            console.log(value);
        }
    );
}

PHP:

$qry = 
    'SELECT * 
    FROM tasks
    WHERE npc_id_fk = 1';

$result = $mysqli->query($qry) or die(mysqli_error($mysqli));

while ($row = $result->fetch_assoc()) {
    echo json_encode($row);
}   

为什么浏览器会输出nulln?


编辑:关注this blog on encoding and decoding UTF-8后,我尝试了:

console.log(decodeURIComponent(value)); //输出:n?


编辑2:

连接:

<?php 
$mysqli = new mysqli("localhost", "root", "", "my_db");

if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (Error code: " . $mysqli->connect_errno . ")... " . $mysqli->connect_error;
}
?>

开始我的phpscripts.php文件:

<?php
include 'runDB.php';
mysql_set_charset($mysqli, "utf8");

的index.php:

<!DOCTYPE html>
<html>
    <head>
        <title>Playground</title>
        <meta charset="UTF-8">

1 个答案:

答案 0 :(得分:1)

在您的HTML标头中添加:

<meta charset="UTF-8">

在PHP Mysql调用中添加:

mysql_set_charset('utf8',$connectToDBVar);

在您的db mysql_connect之后但在查询之前