dongti7838
2014-05-15 01:00
浏览 160

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

I have the following column in my database with UTF-8 encoded letters:

  • chineseWords

    nǐ hǎo

console.log(value) gives: null


If I change them to non UTF-8,

  • chineseWords

    ni hao

console.log(value) gives: ni hao


If I just keep one word

  • chineseWords

console.log(value) gives: 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);
}   

Why would the browser be outputting null and n??


EDIT: following this blog on encoding and decoding UTF-8, I tried:

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


EDIT 2:

Connect:

<?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;
}
?>

Start of my phpscripts.php file:

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

index.php:

<!DOCTYPE html>
<html>
    <head>
        <title>Playground</title>
        <meta charset="UTF-8">
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douzi7890 2014-05-15 01:17
    已采纳

    In your HTML Header add:

    <meta charset="UTF-8">
    

    In your PHP Mysql call add:

    mysql_set_charset('utf8',$connectToDBVar);
    

    after your db mysql_connect but before your query

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题