[英]javascript access function from another namespace in namespaced ajax functions callback
I need some help with my javascript code. 我的JavaScript代码需要一些帮助。 I just recently started using namespaces and I have a problem which I am not able to solve.
我刚开始使用名称空间,但遇到了一个我无法解决的问题。
I have two files data.js and themes.js with a namespace on each data and themes respectively. 我有两个文件data.js和themes.js ,分别在每个数据和主题上都有一个命名空间。 On data namespace I have a function to perform an ajax call like this:
在数据名称空间上,我有一个函数可以执行如下所示的ajax调用:
var data = data || {};data = {
get_companies: function (id) {
$.ajax({
//blah blah blah
});
}
}
and in the themes namespace i have a function like this: 在主题名称空间中,我具有如下功能:
var themes = themes || {};
themes = {
themeAdd: function () {
//blah blah
$.ajax({
//blah blah
success: function (data) {
data.get_companies('#someid');
}
});
}
}
The problem is, while I can access data.get_companies
from themes.js file and console, when I try to call it inside ajax callback it produces an error (data.get_companies is not a function). 问题是,虽然我可以从themes.js文件和控制台访问
data.get_companies
, 但是当我尝试在ajax回调中调用它时,它会产生错误(data.get_companies不是函数)。 How can I fix that and why I can't access this function in ajax callbacks? 如何解决该问题以及为什么无法在Ajax回调中访问此函数?
In your ajax success
callback change the name of the argument passed to it: 在您的ajax
success
回调中,更改传递给它的参数的名称:
$.ajax({
//blah blah
success: function (response) {
data.get_companies('#someid');
}
};
At the moment you define an anonymous function with an arument called data
, so inside this function data
is what has been received by AJAX request, not your global data
object. 现在,您定义了一个带有名为
data
的变量的匿名函数,因此在该函数内部, data
是AJAX请求已接收的内容,而不是全局data
对象。
You could also try to access it like this: 您也可以尝试像这样访问它:
$.ajax({
//blah blah
success: function (data) {
window.data.get_companies('#someid');
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.