2011-02-18 276 views
1

我有一些变量想通过AJAX调用:将变量传递给AJAX

例如,

var moo = "cow noise"; 

$.ajax({ 
    type: "POST", 
    url: "", 
    data: "", 
    success: function(data){ 
      //return the variable here 
      alert(moo); 
    } 
}); 

但是,moo回来未定义。

note,我已经离开urldata空故意 - 它们被填充到我的代码中。

+0

我无法检测到任何问题。请提供实际的代码或工作错误。 – Exelian 2011-02-18 14:00:28

+0

请包括实际的代码。你目前的例子,如果完全罚款。 – 2011-02-18 14:05:51

+0

什么问题。我没有看到任何错误? – 2011-02-18 14:08:22

回答

6

我猜你的代码可能已被包裹在$(function(){ ... });作为jQuery的事情。删除var将使其基本window.moo = "cow noise";哪些工作,但污染名称空间是不是你想要的。

不要试图污染全局命名空间,它会让你的其他代码很难调试。 使用封闭应该解决您的问题:

var moo = "cow noise"; 

(function(moo){ 
    $.ajax({ 
     type: "POST", 
     url: "", 
     data: "", 
     success: function(data){ 
      //return the variable here 
      alert(moo); 
     } 
    }); 
})(moo); 
3

这应该工作,看不出你的代码有什么问题。 Live demo

2

只要变量是相同的功能$.ajax -call中定义的,你应该能够使用moosuccess -callback内,因为它是瓶盖内..

但是,如果ajax - 呼叫是在别处进行的,您必须确保moo在相同的范围内。这可能就像这样:

function thatDefinesTheVariable() { 
    var moo = 'cow noise'; 
    makeAjaxCall(moo); 
} 

function makeAjaxCall (moo) { 
    $.ajax({ 
    type: "POST", 
    url: "", 
    data: "", 
    success: function(data){ 
      //return the variable here 
      alert(moo); 
    } 
    }); 
}