【问题标题】:Unexpected error when posting back json value using PHP使用 PHP 回发 json 值时出现意外错误
【发布时间】:2013-09-10 02:33:13
【问题描述】:

我正在使用 Ajax 从我的服务器端代码 PHP 向我的客户端发回一些数据,这就是它的完成方式

//server side
$json="{
"payout_history":"0",
"round_shares":"1816",
"workers":
   {
    "jbo.5970":
      {
        "alive":"1",
        "hashrate":"1253"
      },
    "jbo.5970cpu":
      {
        "alive":"1",
        "hashrate":"21"
      },
    "jbo.5970-2":
      {
        "alive":"1",
        "hashrate":"1062"
      }
  }
}";
echo json_encode($json);

我在 firebug 的响应页面中收到此错误,我无法弄清楚它有什么问题

    <br />
<b>Parse error</b>:  syntax error, unexpected 'payout_history' (T_STRING) in         
<b>C:\xampp\htdocs\exercise5json\display.php</b> on line <b>38</b><br />

【问题讨论】:

    标签: php jquery ajax


    【解决方案1】:

    您没有正确嵌套引号。您需要将 JSON 字符串括在单引号中,而不是双引号:

    $json = '{"myTag":"myData"}';
    

    或者更好 - 将数组创建为 PHP 数组并使用 json_encode() 为您生成 JSON。

    【讨论】:

    【解决方案2】:

    更简单的方法是将您的数据设为array 并将其传递给json_encode(),例如:

    $json = array(
        "payout_history" => 0,
        "round_shares"  => 1816
        ....
    );
    echo json_encode($json);
    

    【讨论】:

      【解决方案3】:

      代码中的问题在于您使用引号设置$json 字符串的方式。

      查看有关使用引号的 PHP 文档: http://php.net/manual/en/language.types.string.php

      // Outputs: Arnold once said: "I'll be back"
      echo 'Arnold once said: "I\'ll be back"';
      

      不过,正如@Sudhir 之前所说,最好有一个数组并输出 JSON using the json_encode function correctly

      $json = array(
          "payout_history" => 0,
          "round_shares"  => 1816
          // ....
      );
      header("Content-Type: application/json");
      echo json_encode($json);
      

      【讨论】:

        猜你喜欢
        • 2014-03-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-26
        • 1970-01-01
        • 2013-07-06
        • 1970-01-01
        相关资源
        最近更新 更多