【问题标题】:Coffeescript $.ajax result shown as undefindCoffeescript $.ajax 结果显示为未定义
【发布时间】:2011-12-14 13:32:50
【问题描述】:

我使用前端框架并想要呈现一个页面。为此,我使用了一个初始化程序,该初始化程序调用一个对后端执行 $.ajax 调用的函数。但是,尽管在 chrome 开发工具中请求成功,但每次我执行 console.log 时,它都会返回未定义。后端发送正确的结果,但没有显示出来。

  initialize: =>
    @build_recent()
    @payload=@recent_data
    console.log(@payload)

  render: =>
    $(@el).append homeTemplate(@payload)
    @

  build_recent: =>
    $.ajax(
      url: '/build_recent'
      dataType: 'text/json'
      type: 'GET'
      success: (data) =>
        @recent_data = data
    )

更新:

只用了render(),没有用initialize等函数,我终于这样解决了:

  render: =>
    $.ajax(
      url: '/build_recent/'
      dataType: 'json'
      type: 'GET'
      success: (data) =>
        @payload = data
        $(@el).append homeTemplate(@payload)
        return @
    )

原来问题只是这个dataType: 'json'之前我用dataType: 'text/json'

现在效果很好

【问题讨论】:

    标签: jquery coffeescript


    【解决方案1】:

    您的咖啡脚本呈现给:

    var _this = this;
    
    ({
      initialize: function() {
        _this.build_recent();
        _this.payload = _this.recent_data;
        return console.log(_this.payload);
      },
      render: function() {
        $(_this.el).append(homeTemplate(_this.payload));
        return _this;
      },
      build_recent: function() {
        return $.ajax({
          url: '/build_recent',
          dataType: 'text/json',
          type: 'GET',
          success: function(data) {
            return _this.recent_data = data;
          }
        });
      }
    });
    

    并且您不能从 ajax 语句返回。你必须使用回调!

    所以你渲染的js代码可以改成:

    ({
      initialize: function() {
        _this.build_recent();
        //moved into callback
      },
      render: function() {
        $(_this.el).append(homeTemplate(_this.payload));
        return _this;
      },
      build_recent: function() {
        return $.ajax({
          url: '/build_recent',
          dataType: 'text/json',
          type: 'GET',
          success: function(data) {
            _this.recent_data = data;
            //in callback
            _this.payload = _this.recent_data;
            console.log(_this.payload);
            //prob want to render:
            _this.render();
          }
        });
      }
    });
    

    【讨论】:

    • 实际上,如果您在 ajax 选项中设置 async = false ,您可以设法直接返回一个值(但它会冻结页面,所以我不推荐它)
    • 对,这是一个异步问题。如果您希望 build_recent 只进行 Ajax 调用,并且您想在该调用之后执行某些操作,那么 build_recent 需要进行回调。
    • @Neal 我试过了,但它仍然在控制台中返回一个 undefined
    • @Neal 我终于按照你的建议使用回调解决了这个问题,也让它变得简单
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    • 2017-11-30
    • 2014-03-01
    • 1970-01-01
    • 2013-06-12
    • 2016-11-18
    • 1970-01-01
    相关资源
    最近更新 更多