weixin_33725722 2015-02-26 18:44 采纳率: 0%
浏览 357

Javascript跳过Ajax请求

There is an ajax request which retrieves array of data from spring service.

This is the exact code snippet:

getData: function() {
            var me = this;
            var response = [];
            Backbone.ajax({
                url: 'http://localhost:8080/filters/clients',
                success: function(result) {
                    this.response = me.getFilterValues(result);
                    console.log(this.response+" response");
                }
            });
            return this.response;
        },

This is the call to this function from other model

this.set('data', DataProvider.getData(/*pass all selected values here*/));

As you can see on successful ajax request it returns data and passes it to other function which returns an array and then is being used to render view. After some debugging I noticed that at first when this set statement is called ajax is being skipped and so it returns value of undefined. After some time when it tries to access this undefined data object it finally does this ajax successfully but at that point its too late.

Why? Is it because its async and first time it gets the request is being sent and without any wait it goes straight to the next portion of code or what? Debugging shows that first time it comes to ajax it just gets the name and return line thats it.

  • 写回答

1条回答 默认 最新

  • weixin_33725807 2015-02-26 18:56
    关注

    You need to use a callback, that return is being hit while the request is still processing. Here's how you can refactor:

    getData: function(callback) {
            var me = this;
            Backbone.ajax({
                url: 'http://localhost:8080/filters/clients',
                success: function(result) {
                    callback(me.getFilterValues(result));
                }
            });
        },
    

    And the setter:

    DataProvider.getData(function(data) {
        //data is the response from your AJAX call
        this.set('data', data); //'this' may be the wrong context here.
    }); 
    
    评论

报告相同问题?

悬赏问题

  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥15 latex怎么处理论文引理引用参考文献