可能做你想做的事,但我不推荐。方法如下:
function doTheThing() {
var element, to_list;
/* code here that gets element and to_list */
// Modify the post to use a callback and the "text" data type
$.post($(F).attr('action'), $(F).serialize(), handleMove, "text");
// Here's the callback
function handleMove(data) {
eval(data);
}
}
之所以有效,是因为eval 非常特殊,它在调用它的范围内执行(这有点神奇),因此文本eval 评估中的代码可以访问所有变量在调用eval 的范围内。
有点偏离主题,但我会推荐一种基于数据的方法。也许:
function doTheThing() {
var element, to_list;
/* code here that gets element and to_list */
// Modify the post to use a callback and the "json" data type
$.post($(F).attr('action'), $(F).serialize(), handleMove, "json");
// Here's the callback
function handleMove(data) {
if (data.errorMessage) {
/* ...show the error... */
}
else {
moveNode(element, to_list);
}
}
}
...您的服务器返回的位置:
{"errorMessage": "Don't move it!"}
或
{"success": true}
或任何在您的环境中有意义的东西。哎呀,如果它真的只是“它有效”或“这里有一个错误”,你可以使用一个文本协议,其中“OK”意味着好的,其他任何东西都是错误消息(互联网上到处都是基于文本的协议) .我更喜欢更多的结构,但关键是你有选择。
我会发现这种方法更易于维护。当您开始在层之间来回传递代码时,代码依赖于知道范围内变量的名称,这似乎是一个主要的紧密耦合问题。