【问题标题】:Unexpected token, in JSON at position 23意外的令牌,在 JSON 中的位置 23
【发布时间】:2017-03-07 07:24:17
【问题描述】:

Angular 和 HTML 代码:

<!DOCTYPE html>
    <html>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
        <body>
            <div ng-app="myApp" ng-controller="myCtrl">
                <p>Today's welcome message is:</p>
                <h1>{{ myWelcome }}</h1>
            </div>
            <p>The $http service requests a page on the server, and the response is set as the value of the "myWelcome" variable.</p>

            <script>
                var app = angular.module('myApp', []);
    app.controller('myCtrl', function($scope, $http) {
                    $http({
                        method: "GET",
                        url: "http://localhost/dustbin/uxo_data/leaderboard.php"
                    }).then(function mySucces(response) {
                        $scope.myWelcome = response.data;
                    }, function myError(response) {
                        $scope.myWelcome = response.statusText;
                    });
                });
    </script>

        </body>
    </html>

PHP 返回:

{"total":"4","phn":"1"},{"total":"1","phn":"2"}

错误:

angular.min.js:107 SyntaxError: Unexpected token , in JSON at position 23

上面代码中的错误是什么,我在前端使用angular,在后端使用php作为rest-api

【问题讨论】:

  • 返回的数据不是有效的 JSON。至少周围的[] 会丢失。
  • 在php中使用json_encode返回数组。
  • @sachilaranawaka 可以添加相关的PHP代码吗?至少你用错了json_encode()?
  • 你能告诉 php sn-p 你在哪里以及如何使用json_encode() 方法吗?

标签: javascript php angularjs json


【解决方案1】:

您的 JSON 字符串有效,但 JSON 数据不准确。

您需要将数据放在方括号[] 中。

[{"total":"4","phn":"1"},{"total":"1","phn":"2"}]

我想你正在转换 JSON 中的每个对象,并在服务器端用逗号分隔它们。

相反,在 PHP 中创建一个包含所有对象的数组,然后使用内置 json_encode function. 获取 json

$jsonstr = json_encode($arr);

【讨论】:

    【解决方案2】:

    正如评论所说,您缺少[]。如果 php 发送 json 数据,那么你应该 json_encode() 它。

    echo json_encode($object);
    exit();
    

    【讨论】:

      猜你喜欢
      • 2019-05-06
      • 2016-12-13
      • 1970-01-01
      • 1970-01-01
      • 2020-02-05
      • 2021-09-12
      • 2018-10-17
      相关资源
      最近更新 更多