jquery函数中的变量,如何处理全局变量?
我在 jquery 中有一个 ajax 调用,它返回 4 个不同的数组。 我想在 ajax 成功函数之外使用其中的 3 个数组,并且数组中的数据应该可用于某些单击事件。
我只是不知道处理数组变量的最佳方法。 有些人说走向全球是一个坏主意,而另一些人则说没关系..所以
ajax success 函数: 数组
array1、array2 之一需要由其他函数和单击事件使用
function display_results_1(){
$('#myDiv').html(array1.id);
}
$('#binfo').click(function(){
$('#client_info_div').dialog({
$('#myDiv').html(array2.id);
});
})
这是我的 ajax 调用:
$('#c_search').submit(function(){
data = ($(this).serialize());
$.ajax({
url: 'actions/get_company.php',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
success: function(selected){
`doing stuff here`
})
})
我应该在每个不同函数需要时使用单独的 Ajax 调用来获取数据吗?
I have an ajax call in jquery which returns 4 different arrays.
3 of these arrays i want to use outside of the ajax success function and the data in the arrays should be accessible for certain click events.
I just don't know the best way to handle the array variables.
some people say going global is a bad idea and other say its ok.. so
ajax success function:
does stuff with one of the arrays
array1, array2 needs to be used by other functions and click events
function display_results_1(){
$('#myDiv').html(array1.id);
}
$('#binfo').click(function(){
$('#client_info_div').dialog({
$('#myDiv').html(array2.id);
});
})
This is my ajax call:
$('#c_search').submit(function(){
data = ($(this).serialize());
$.ajax({
url: 'actions/get_company.php',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
success: function(selected){
`doing stuff here`
})
})
Should I use separate Ajax calls to get the data when needed for each different function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您绝对不希望变量处于全局范围内,但您可以将所有内容包装在函数中以防止它们处于全局范围内:
通过这样做,您将确保代码也在页面加载时运行,请注意$() 包装函数。
有关详细信息,请参阅 http://api.jquery.com/ready/。
与之前的答案相反,走向全球并不是一个好主意。您最终可能会拥有使用相同变量的多个 JavaScript 片段。
You definitely don't want your variables in the global scope, but you could wrap everything in a function to prevent them from being in the global scope:
By doing this you'll ensure that the code is also running on page load, notice the $() wrapping the function.
See http://api.jquery.com/ready/ for more info.
Contrary to the previous answers, going global is NOT a good idea. You may end up having multiple pieces of JavaScript using the same variables.
将数组分配给 ajax success 函数内的 window 对象:
Assign the arrays to the window object inside the ajax success function:
如果您需要在 success 函数外部使用它,请在函数外部设置一个变量。
不要担心“走向全局”,如果您需要函数范围之外的变量,请将其设置在您需要的地方。一个好地方可能是在
$(document).ready()
的开头If you need it to be used outside the success function then set a variable outside the function.
Don't worry about "going global", if you need a variable outside the scope of a function, then set it where you need it. A good place may be at the beginning of
$(document).ready()