Javascript 匿名函数内部范围
我试图让一个函数从 ajax 调用返回数据,然后我可以使用它。问题是函数本身被许多对象调用,例如:
function ajax_submit (obj)
{
var id = $(obj).attr('id');
var message = escape ($("#"+id+" .s_post").val ());
var submit_string = "action=post_message&message="+message;
$.ajax({
type: "POST",
url: document.location,
data: submit_string,
success: function(html, obj) {
alert (html);
}
});
return false;
}
这意味着在匿名“成功”函数内部我无法知道调用的 obj (或 id)实际上是什么。我能想到的唯一方法是将 id 附加到文档,但这似乎有点太粗糙了。还有另一种方法可以做到这一点吗?
I am trying to make a function return data from an ajax call that I can then use. The issue is the function itself is called by many objects, e.g.:
function ajax_submit (obj)
{
var id = $(obj).attr('id');
var message = escape ($("#"+id+" .s_post").val ());
var submit_string = "action=post_message&message="+message;
$.ajax({
type: "POST",
url: document.location,
data: submit_string,
success: function(html, obj) {
alert (html);
}
});
return false;
}
Which means that inside the anonymous 'success' function I have no way of knowing what the calling obj (or id) actually are. The only way I can think of doing it is to attach id to document but that just seems a bit too crude. Is there another way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用封闭范围中的变量,这种技术称为“闭包”。所以:
You can use variables from the enclosing scope, a technique called "closure". So:
如果您尝试通过 ajax 将 html 加载到页面上,您可能需要考虑 load() 函数。
If you are attempting to load html onto the page via ajax you may want to consider the load() function.
JavaScript 中的函数被包含在定义它们的范围内(这是一个闭包)。在这种情况下,每次调用 ajax_submit() 时都会创建一个新的匿名成功回调函数,因此父作用域中的所有变量始终可以访问。
您的代码应该可以正常工作。如果您想要一个回调函数,可以将其作为参数传递给
ajax_submit()
并像这样调用:Functions in JavaScript become enclosed in the scope in which they are defined (this is a closure). In this case, a new anonymous success callback function is created every time
ajax_submit()
is called, so all the variables from the parent scope will always be accessible.Your code should work just fine as is. If you want to have a callback function, it can be passed as an argument to
ajax_submit()
and called like this:变量
obj
、id
和message
在匿名函数中都可用。这是因为 Javascript 中有一个名为闭包的功能,我建议您仔细阅读该功能。
闭包的一般要旨是,函数将永远可以访问其定义范围内存在的变量。
这样做的结果是您可以这样做:
一整天(但请注意,
obj success 函数中的
参数将优先于 ajax_submit 函数中的 obj 变量。)The variables
obj
,id
andmessage
are all available within the anonymous function.This is because of a feature in Javascript called closures, which I advise you read up on.
The general gist of a closure is that a function will forever have access to the variables that were present in the scope it was defined in.
The result of this is that you can do:
all day long (but note that the
obj
parameter in the success function will take precedence over theobj
variable in your ajax_submit function.)