我一整天都在处理。 “sendResponse”是一个回调函数。由于我正在处理ajax请求,因此我必须使用它来在请求后检索数据。我只是无法通过一个处理ajax响应的匿名函数传递它。这里的解决方案是什么?
runningTimeEntry: function (sendResponse) {
TogglButton.ajax('/time_entries/current', {
method: 'GET',
onLoad: function (xhr) {
var responseData = JSON.parse(xhr.responseText);
sendResponse(responseData.data); // this line doesn't work
}
});
},
ajax: function (url, opts) {
var xhr = new XMLHttpRequest(),
method = opts.method || 'GET',
baseUrl = opts.baseUrl || TogglButton.$newApiUrl;
xhr.open(method, baseUrl + url, true);
if (opts.onLoad) {
xhr.addEventListener('load', function () {
opts.onLoad(xhr);
});
}
if (TogglButton.$user) {
xhr.setRequestHeader('Authorization', 'Basic ' + btoa(TogglButton.$user.api_token + ':api_token'));
}
xhr.send(JSON.stringify(opts.payload));
},
简而言之,这会返回{test:“test”}:
runningTimeEntry: function (sendResponse) {
TogglButton.ajax('/time_entries/current', {
method: 'GET',
onLoad:
sendResponse({
test: 'test'
});
});
},
这不是:
runningTimeEntry: function (sendResponse) {
TogglButton.ajax('/time_entries/current', {
method: 'GET',
onLoad: function (xhr) {
sendResponse({
test: 'test'
}); // this line doesn't work
}
});
},