我一直难以理解when(
如何传递数据。在本例中,我需要在then()
语句中使用when()
的id。然而,它未能解决。我听说过一些关于when()
返回deferred的事情,但我似乎不明白如何使用它。
// 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();
})
};
idx
appear undefined
at url: 'api/datapoints/' + idx
?
$.ajax()
调用在$.when()
或.done()
中没有被return
调用?
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();
})
};