Javascript 将UTF-8编码的JSON从DB解析为JS
我的数据库中有以下列,其中包含UTF-8编码字母:Javascript 将UTF-8编码的JSON从DB解析为JS,javascript,php,json,encoding,utf-8,Javascript,Php,Json,Encoding,Utf 8,我的数据库中有以下列,其中包含UTF-8编码字母: 中文单词 nǐhǎo console.log(值)给出:null 如果我把它们改成非UTF-8 中文单词 倪浩 console.log(值)给出:ni hao 如果我只说一句话 中文单词 nǐ console.log(值)给出:n? jQuery: function getData (functionToRun) { $.getJSON("phpscripts.php", {"_functionToRun" : f
- 中文单词 nǐhǎo
null
如果我把它们改成非UTF-8
- 中文单词 倪浩
ni hao
如果我只说一句话
- 中文单词 nǐ
n?
jQuery:
function getData (functionToRun) {
$.getJSON("phpscripts.php", {"_functionToRun" : functionToRun},
function (returned_data) {
var value = returned_data.chineseWords;
console.log(value);
}
);
}
$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);
}
<!DOCTYPE html>
<html>
<head>
<title>Playground</title>
<meta charset="UTF-8">
PHP:
function getData (functionToRun) {
$.getJSON("phpscripts.php", {"_functionToRun" : functionToRun},
function (returned_data) {
var value = returned_data.chineseWords;
console.log(value);
}
);
}
$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);
}
<!DOCTYPE html>
<html>
<head>
<title>Playground</title>
<meta charset="UTF-8">
为什么浏览器会输出null
和n?
编辑:下面,我尝试了:
console.log(解码组件(值))代码>//输出: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;
}
?>
连接:
<?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;
}
?>
index.php:
function getData (functionToRun) {
$.getJSON("phpscripts.php", {"_functionToRun" : functionToRun},
function (returned_data) {
var value = returned_data.chineseWords;
console.log(value);
}
);
}
$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);
}
<!DOCTYPE html>
<html>
<head>
<title>Playground</title>
<meta charset="UTF-8">
游乐场
在HTML标题中添加:
<meta charset="UTF-8">
在db mysql_连接之后但在查询之前JS解析UTF8字符串没有问题。@Cookie Monster你知道为什么它会输出null
吗?不,我不知道。HTTP头没有正确设置?也许可以尝试发出一个本机XHR请求,并查看响应文本,看看它是否符合您的预期。