2015-08-21 20 views
0

我一直無法理解when()如何傳遞數據。在這個例子中,我需要使用then()語句中when()的id。但是,它無法解決。我聽說有關when()返回延遲的一些信息,但似乎無法理解如何使用它。從()中獲取數據的時候()

// retrieve the id of selected point from the database, and remove the 
// point 
var deletePointByLocation = function (lat, lng) { 
    $.when(function() { 
     var filters = [ 
      { 
       'name': 'lat', 
       'op': 'eq', 
       'val': lat 
      }, 
      { 
       'name': 'lng', 
       'op': 'eq', 
       'val': lng 
      } 
     ]; 

     $.ajax({ 
      headers: { 
       'Accept': 'application/json', 
       'Content-Type': 'application/json' 
      }, 
      url: 'api/datapoints', 
      data: {"q": JSON.stringify({"filters": filters})}, 
      dataType: "json", 
      type: 'GET' 
     }) 
    }).then(function (data) { 
     var idx 
     $.ajax({ 
      headers: { 
       'Accept': 'application/json', 
       'Content-Type': 'application/json' 
      }, 
      url: 'api/datapoints/' + idx, 
      type: 'DELETE' 
     }) 
    }).done(function() { 
     var point = new google.maps.LatLng(lat, lng); 
     _.forEach(mapCircles, function (circle) { 
      if (circle.getCenter().equals(point)) { 
       circle.setMap(null); 
       var idx = mapCircles.indexOf(circle); 
       mapCircles.splice(idx, 1); 
       num--; 
      } 
     }); 
     toggleInfoDisplays(); 
    }) 
}; 

回答

0

idx出現undefinedurl: 'api/datapoints/' + idx

$.ajax()調用不是 ed $.when().done()

mapCircles沒有出現在.done()定義?

嘗試

var deletePointByLocation = function (lat, lng) { 
    // add `return` before `$.when()` 
    return $.when(function() { 
     var filters = [ 
      { 
       'name': 'lat', 
       'op': 'eq', 
       'val': lat 
      }, 
      { 
       'name': 'lng', 
       'op': 'eq', 
       'val': lng 
      } 
     ]; 

     return $.ajax({ 
      headers: { 
       'Accept': 'application/json', 
       'Content-Type': 'application/json' 
      }, 
      url: 'api/datapoints', 
      data: {"q": JSON.stringify({"filters": filters})}, 
      dataType: "json", 
      type: 'GET' 
     }) 
    }).then(function (data) { 
     var idx; // what is `idx` ? 
     // add `return` before `$.ajax()` 
     return $.ajax({ 
      headers: { 
       'Accept': 'application/json', 
       'Content-Type': 'application/json' 
      }, 
      url: 'api/datapoints/' + idx, // what is `idx` ? 
      type: 'DELETE' 
     }) 
    }).done(function() { 
     var point = new google.maps.LatLng(lat, lng); 
     // what is `mapCircles` ? 
     _.forEach(mapCircles, function (circle) { 
      if (circle.getCenter().equals(point)) { 
       circle.setMap(null); 
       var idx = mapCircles.indexOf(circle); 
       mapCircles.splice(idx, 1); 
       num--; 
      } 
     }); 
     // what is `toggleInfoDisplays` ? 
     toggleInfoDisplays(); 
    }) 
}; 
+0

林呼籲在該部分的一些全局變量等功能,這就是你所看到的。我想從when()中得到id,並把它放在idx變量中 – Praetore

+0

@Praetore _「想要從when()中得到id,並將它放在idx變量」_'data'變量處於'.then ()'應該包含'$ .ajax()'的響應,可以通過從'$ .ajax()'響應中檢索'id'來設置'idx' – guest271314