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 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥15 python爬取bilibili校园招聘网站
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件