【问题标题】:Calling Ajax service using callback function使用回调函数调用 Ajax 服务
【发布时间】:2016-04-28 01:56:11
【问题描述】:

我正在尝试使用 ajax 调用 Web 服务,然后将结果传递给角度控制器。我无法从回调函数中获取值以传递给范围变量。我认为这只是我对回调函数如何工作的理解不好。

代码如下:

function ajaxKimono(callback) {

    $.ajax({
          url:"https://www.kimonolabs.com/api/cveeggn4?apikey=NWYzkeJpFDtb4aOYd6yD96L5PdLuZHjo",
          crossDomain: true,
          dataType: "jsonp",
          success: callback,
          error: function (xhr, status) {
            //handle errors
            console.log(xhr);
            console.log(status);
          }
        });

};

angular.module('app').controller('gifCtrl', function(){
    var self = this;
    var gifs = [];

    ajaxKimono(function(result){
        var collection = result.results.collection1;

        $.each(collection, function(i, item){
            gifs.push({ gif: item.property5.href});
        });

        //this outputs the correct data
        //so i know the ajax call is working correctly
        console.log(gifs);

        self.gifCollection = gifs;

    });

    //something about the scope is messing me up
    //this outputs nothing...
    console.log(self.gifCollection);

});

【问题讨论】:

  • 您的回调函数完美运行。你不明白,ajax 请求是异步的。在执行和处理 ajax 请求之前,首先执行不输出任何内容的 console.log。然后,执行 ajax 请求并调用您的回调。只有现在 console.log in 回调才会被执行。这是正常情况。因此,当您执行一些 ajax 请求时,您将在控制器中进行初始化。
  • 在 AngularJS 中,您应该使用 $http 服务进行 ajax 调用 docs.angularjs.org/api/ng/service/$http

标签: javascript jquery angularjs ajax


【解决方案1】:

正如 cmets 中提到的,我想问题是您的 console.log 在您的请求完成之前被调用。

将您的 http 请求放在单独的工厂或服务中。这使得测试和重用变得更容易。请注意使用 Angular 的 $http 快捷方法返回 promise

app.factory('DataService', function($http) {
  var getValues= function() {
    return $http.jsonp("/api/...") // returns a promise
  };

  return {
    getValues: getValues
  }
});

然后在你的控制器中:

myApp.controller('MyController', function ($scope, DataService) {     
    DataService.getValues().then(
    function(){
      // successcallback
    },
    function(){
      // errorcallback
    })   
});

注意上面的代码我没有实现,但是应该给你提供一个大纲

【讨论】:

  • 我添加了工厂和控制器。并且有一些有趣的结果。我没有从“// successcallback”区域内得到任何东西。但它似乎解决了完全独立的 ajax 调用。在我的 codepen 上检查一下(给它大约 5 秒的时间来加载)codepen.io/bipinbipin/pen/mVpvyB
  • 仍在尝试使用 sjokkogutten 建议的方法来完成这项工作。目前它对 .then() TypeError: Cannot read property 'then' of undefined 不满意
  • 抱歉,忘记退货声明了。更新了你的代码笔
  • 做到了。我的和服服务仍然有问题。需要研究 jsonp,我读到的所有内容都说和服服务是 jsonp 而不是原始 json。 (即使 .ajax 请求也有 dataType:"jsonp")但是当我使用 Angular $http.jsonp 我得到:kimono-service.html:1 Refused to execute script from 'kimonolabs.com/api/cveeggn4?apikey=NWYzk...' 因为它的 MIME 类型( 'application/json') 不可执行,并且启用了严格的 MIME 类型检查。 kimono-service-app.js:55 对象 {数据:未定义,状态:404,配置:对象,状态文本:“错误”}
  • 我尝试将$http.jsonp 替换为$http.get 并返回Object { data: null, status: 0, headers: Yc/<(), config: Object, statusText: "" }。它还返回:Cross-Origin Request Blocked:The Same Origin Policy disallows reading the remote resource at kimonolabs.com/api/etc...(原因:CORS 标头“Access-Control-Allow-Origin”缺失)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-18
  • 1970-01-01
  • 2023-03-08
相关资源
最近更新 更多