Javascript jQuery变量范围

Javascript jQuery变量范围,javascript,jquery,Javascript,Jquery,我有以下功能: function postToDrupal(contacts, source, owner) { (function ($) { $.post("/cloudsponge-post",function(contacts) { alert(contacts); }); }(jQuery)); } 我遇到的问题是,联系人似乎是在jQuery闭包外部定义的,而不是在jQuery闭包内部定义的。我是javascript新手,所以这让我很困惑。如何才能

我有以下功能:

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

我遇到的问题是,联系人似乎是在jQuery闭包外部定义的,而不是在jQuery闭包内部定义的。我是javascript新手,所以这让我很困惑。如何才能将其用于发布联系人?

您不需要在$.post()函数中再次将
联系人
作为参数

如果您这样做,您将使另一个变量成为$.post的局部变量

在javascript中,变量是函数的局部变量,而不是块

我喜欢这篇文章:


这是一本关于理解javascript作用域的非常好的读物。还有一种叫做“提升”的东西,你应该知道

当您将该名称重新用作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));
}
函数postToDrupal(联系人、来源、所有者){
(函数($){

$.post(“/cloudspinepost”,function(data){/您可以将其用作syncronus ajax调用。重写代码并使用它

function postToDrupal(contacts, source, owner) {
var result = undefined;
    $.ajax( {
            type : 'GET',
            url : '/cloudsponge-post',
            async: false,
            success : function(contacts) {          
                result = contacts;
            }
        });
        return result;
}
试试这个:

function postToDrupal(contacts, source, owner) {
  $.post("/cloudsponge-post",function(responseData) {
    alert(responseData);
    alert(contacts);
  });
}

联系人是您要发送到Cloudscape post url的数据吗?我说得对吗?如果不是,您可以再详细说明一下。a)在这种情况下使用async:false是完全不必要的错误建议,b)这并不能解决OP的问题(即无法访问成功回调中的原始
联系人
变量)好的,为了澄清一下,如果我想发布“联系人”,我需要:$.post(“/CloudSpoonePost”),联系人,函数(数据){