【问题标题】:Unable to parse JSON with AngularJS无法使用 AngularJS 解析 JSON
【发布时间】:2014-02-24 09:06:05
【问题描述】:

我刚开始使用 AngularJS 并尝试了一个非常基本的示例。该网页包含一个按钮,单击该按钮我从服务器请求一个 json。 但是每当我单击按钮时,代码都会执行错误函数中的部分。

HTML 文件

<!DOCTYPE html>
<head>
    <title> step 4</title>
</head>

<body ng-app="step4App">
    <div ng-controller="FriendsCtrl">

        <button ng-click="loadFriends()">Load Friends</button>
    </div>

    <script src="angular.min.js"></script>
    <script src="xml2json.js"></script>
    <script src = "step4.js"></script>
</body>
</html>

JS

var app = angular.module("step4App",[]);

app.controller("FriendsCtrl", function($scope,$http) {
    $scope.loadFriends = function(){



        $http({method:'GET',url:'http://localhost:8080/test.jsp', params:{name:"abc",no:"LBF1151638"}}).success(function(data) {
            $scope.friends = data;
            document.write('<p>two</p>');
            document.write(data);
        }).error(function() {

            alert("error");
            });
            }

});

到目前为止,jsp 页面正在返回此 json 响应。

{"response":{"numFound":0,"start":0,"docs":[]}}

但我无法理解,为什么它总是执行错误函数。

我在浏览器控制台中检查了正在发出请求并收到 47 字节的响应(等于 JSON 中的字符数)。但它不打印 JSON。

【问题讨论】:

    标签: javascript html json angularjs


    【解决方案1】:

    服务器上可能发生了错误。尝试使用 FireFox + Firebug 打开页面并检查服务器响应以确保它符合您的预期(检查状态代码和 Content-Type 响应标头)。

    您也可以从命令行运行curl -v http://localhost:8080/test.jsp

    顺便说一句,Angular 在回调中传递了额外的参数。试着提醒他们看看他们是什么。来自http://docs.angularjs.org/api/ng/service/$http:

    $http({method: 'GET', url: '/someUrl'}).
    success(function(data, status, headers, config) {
      // this callback will be called asynchronously
      // when the response is available
    }).
    error(function(data, status, headers, config) {
      // called asynchronously if an error occurs
      // or server returns response with an error status.
    });
    

    【讨论】:

    • 谢谢。我尝试使用萤火虫。它说状态为 200(OK),但 angularJS 说 404。
    • 您可能想检查 JSP 文件中的逻辑,可能有问题。或者确保您的网址中没有拼写错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    • 1970-01-01
    • 2020-12-02
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多