jQuery变量范围

cjm*_*671 0 javascript jquery

我有以下功能:

function postToDrupal(contacts, source, owner) {
  (function ($) {
    $.post("/cloudsponge-post",function(contacts) {
      alert(contacts);
    });
  }(jQuery));
}
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是,联系人似乎是在jQuery闭包之外定义的,但不在其中.我是一个javascript新手,所以这让我很困惑.如何才能发布此消息?

JJJ*_*JJJ 7

当您将名称重新用作AJAX调用的回调函数参数时,您将使用具有相同名称的新变量屏蔽变量.

function postToDrupal(contacts, source, owner) {
  (function ($) {
    $.post("/cloudsponge-post",function(data) {  // <-- !!
      console.log(contacts);  // the first parameter of postToDrupal()
      console.log(data);      // the response from the AJAX call
    });
  }(jQuery));
}
Run Code Online (Sandbox Code Playgroud)