我试图将变量传递给done
回调,但没有运气。
var getDataForCompany = function(company_id) {
$.ajax({
type: "post",
url: url,
data:{
company_id: company_id
}
}).done(function(returnedData, textStatus, jqXHR) {
anotherFn(company_id);
//need to access company_id here, but it is undefined
});
};
我尝试在IIFE中包装整个AJAX请求以尝试创建一个闭包来捕获我的company_id,但
var getDataForCompany = function(company_id) {
($.ajax({
type: "post",
url: url,
data:{
company_id: company_id
}
}).done(function(returnedData, textStatus, jqXHR) {
anotherFn(company_id);
//need to access company_id here, but it is undefined
})(company_id);
};
也没能奏效。这不是正确的方法吗?
答案 0 :(得分:0)
正如评论中所提到的,匿名完成函数应该引用通过getDataForCompany调用传入的company_id。传入时可能只是未定义。下面的代码类似于ajax调用的闭包设置。如果运行该方法,您将看到将记录company_id。
var getDataForCompany = function(company_id) {
var done = function() {
console.log(company_id)
}
done();
};
getDataForCompany("ID")
>>"ID"
getDataForCompany()
>>undefined
答案 1 :(得分:0)
尝试
var getDataForCompany = function(company_id) {
return $.ajax({
type: "POST",
url: url,
data:{
company_id: company_id
}
})
.done(function(returnedData, textStatus, jqXHR) {
var company_id = this.url.split(/company_id=/)[1];
console.log(company_id);
return anotherFn(company_id);
//need to access company_id here, but it is undefined
});
};
var anotherFn = function(company_id) {
return $.ajax({
type: "GET",
url: "https://gist.githubusercontent.com/guest271314/23e61e522a14d45a35e1/raw/62775b7420f8df6b3d83244270d26495e40a1e9d/ticker.json",
data:{
company_id: JSON.stringify(company_id)
},
dataType: "json"
}).done(function(data) {
console.log(this.url.split(/company_id=/)[1])
})
};
var getDataForCompany = function(company_id) {
return $.ajax({
type: "GET",
url: "https://gist.githubusercontent.com/guest271314/23e61e522a14d45a35e1/raw/62775b7420f8df6b3d83244270d26495e40a1e9d/ticker.json",
data:{
company_id: company_id
},
dataType: "json"
}).done(function(returnedData, textStatus, jqXHR) {
var company_id = this.url.split(/company_id=/)[1];
console.log(company_id);
return anotherFn(parseInt(company_id) + 1);
//need to access company_id here, but it is undefined
});
};
getDataForCompany(1);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
&#13;