将变量传递给AJAX

Bar*_*der 1 javascript ajax jquery

我有一些变量,我想传递给AJAX调用:

例如

var moo = "cow noise";

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

但是,moo回来未定义.

请注意,我故意离开urldata清空 - 它们填充在我的代码中.

ccp*_*ava 8

我想你的代码可能已被包装$(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);
Run Code Online (Sandbox Code Playgroud)