【问题标题】:JSON.parse doesn't parse JSON correctlyJSON.parse 无法正确解析 JSON
【发布时间】:2014-04-02 17:51:17
【问题描述】:

我正在尝试使用 JSON.parse 从文本中解析 JSON。

我的问题是我的 JSON 被编码为 UTF8,但 JSON.parse 不会用 UTF8 解析它。

这是我的build_workout_functions.js 代码:

function getExercies(){
    var xmlhttp;
    xmlhttp=new XMLHttpRequest();
    xmlhttp.onreadystatechange=function(){

  if (xmlhttp.readyState==4 && xmlhttp.status==200){
    console.log(xmlhttp.responseText);
    var obj = JSON.parse(xmlhttp.responseText);
    console.log(obj);
      }
   }

xmlhttp.open("POST","get_exercise_list.php",true);

var e = document.getElementsByName("muscles");
var strUser = e[0].options[e[0].selectedIndex].text;

console.log(strUser);

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.send("muscle=" + strUser);
}

PHP 代码:

<?php
header("Content-type: application/json; charset=utf-8");
if(isset($_POST['muscle'])){
    echo $_POST['muscle'];
    $response["test"] = $_POST['muscle'];
    echo json_encode($response);
}
?>

HTML 页面:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
    <link rel="stylesheet" type="text/css" href="styles.css" />
    <script src="build_workout_functions.js" charset="UTF-8"></script>
</head>
<body id="login-bg"> 
    <div class="workout_table">
        <select name="muscles" onchange="getExercies()">
            <option value="legs">טסט</option>
            <option value="back">טסט2</option>
        </select>
        <select name="exericse"><select>
    </div>
</body>
</html>

在我的开发控制台(我正在使用 Chrome)中,我看到了这个日志:

יד קדימית build_workout_functions.js:33
XHR finished loading: "****************". 
build_workout_functions.js:38
יד קדימית{"test":"\u05d9\u05d3 \u05e7\u05d3\u05d9\u05de\u05d9\u05ea"} 

在我的日志中,我看到当我回显我的 POST 时,我可以看到它编码正确。

但我的JSON.parse 没有这样做。我该如何解决这个问题?

【问题讨论】:

  • 到底是什么问题,什么是“错误”解析?顺便说一句,您的日志与您的代码不匹配。
  • 你的php版本是多少?
  • 您是否遇到错误或其他问题?当您说“不起作用”时,它有助于解释您的意思
  • 也许这个链接会对你有所帮助:stackoverflow.com/questions/6771938/…
  • 我使用了这个代码:json_encode($response, JSON_UNESCAPED_UNICODE) 很好。感谢您的帮助

标签: javascript php ajax json utf-8


【解决方案1】:

我用这个来解决问题:

json_encode($response, JSON_UNESCAPED_UNICODE)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-24
    • 1970-01-01
    • 2013-10-14
    • 2012-08-12
    • 2021-09-24
    • 1970-01-01
    • 2013-02-16
    相关资源
    最近更新 更多