【问题标题】:Json not working with angular.jsJson 不使用 angular.js
【发布时间】:2013-08-05 13:19:58
【问题描述】:

我正在尝试从外部域获取预测信息,但这似乎还不起作用。 Angular 和 jQuery 都已加载,但 HTML 中没有显示任何内容。 Chrome 也不会报告错误消息。

        var currentCityread = "Eindhoven";
        var api1 = 'http://api.openweathermap.org/data/2.5/forecast/daily?q='+currentCityread+'&cnt=10&mode=json&units=metric&APPID=000000000000000&callback=?';
        var api2 = 'http://api.openweathermap.org/data/2.5/weather?q='+currentCityread+'&mode=json&units=metric&APPID=000000000000000&callback=?'
        function ReadJson($scope) {
            $.ajax({
              dataType: "json",
              url: api1,
              }).done(function (output) {
                $scope.jsonTotal = output.list[0].temp.day+output.list[1].temp.day+output.list[2].temp.day+output.list[3].temp.day+output.list[4].temp.day+output.list[5].temp.day+output.list[6].temp.day+output.list[7].temp.day+output.list[8].temp.day+output.list[9].temp.day;
                $scope.jsonCalcu = Math.round($scope.jsonTotal / 10);
                $scope.jsonCurrent = Math.round(output.list[0].temp.day);
                $scope.jsonCurrent2 = Math.round(output.list[1].temp.day);
                $scope.jsonCurrenticon2 = output.list[1].weather[0].icon;
                $scope.jsonCurrent3 = Math.round(output.list[2].temp.day);
                $scope.jsonCurrenticon3 = output.list[2].weather[0].icon;
            });
            $.ajax({
              dataType: "json",
              url: api2,
              }).done(function (outputcurrent) {
                $scope.jsonCurrenticon = outputcurrent.weather[0].icon;
            });
        }

【问题讨论】:

  • 在完成方法回调中尝试$scope.$apply(),在赋值之后
  • 这段代码在哪里? ReadJson 是控制器吗?否则我不知道你如何在那里注入范围。无论如何,为什么不使用$http
  • 我不认为 jquery ajax 可以使用 angular 的范围。改用 $http
  • 此代码是一个外部 javascript 文件。 ReadJson 确实是一个控制器。 $http 不会成功,因为这可能是不安全的,跨域:)。
  • 这毫无意义。它们几乎处于相同的安全级别。关键是你不能像这样使用 jQuery 来访问 Angularjs 范围。

标签: javascript jquery ajax json angularjs


【解决方案1】:

由于您在角度执行上下文之外的回调之后更新范围,因此您需要使用$scope.$apply()

但是正如其他人在他们的 cmets 中提到的那样,$http 可以使用,JSONP 因为请求是跨域的。

【讨论】:

    【解决方案2】:

    我认为同源策略禁止您执行跨域查询。您可以做的是在服务器端执行查询,并将结果返回给浏览器。另一种解决方法是使用 jsonp。但不推荐使用,因为它不安全。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多