Passing variables through to AJAX
I have some variables that I would like to pass into an AJAX call:
e.开发者_如何学Cg.
var moo = "cow noise";
$.ajax({
type: "POST",
url: "",
data: "",
success: function(data){
//return the variable here
alert(moo);
}
});
However, moo
comes back undefined.
note, I've left url
and data
empty on purpose - they are populated in my code.
I guess your code might have been wrapped in $(function(){ ... });
as an jQuery thing. remove var
will make it basically window.moo = "cow noise";
Which works, but pollutes the namespaces which is not what you want.
Do not try to pollute the global namespace, it will make your other code hard to debug. Use closure which should solve your issue:
var moo = "cow noise";
(function(moo){
$.ajax({
type: "POST",
url: "",
data: "",
success: function(data){
//return the variable here
alert(moo);
}
});
})(moo);
This should work, can't see anything wrong with your code. Live demo.
as long as the variable is defined inside the same function as the $.ajax
-call, you should be able to use moo
inside the success
-callback since it's inside the closure..
However, if the ajax
-call is made elsewhere, you have to ensure that moo
is inside the same scope. This could be done like this:
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);
}
});
}
精彩评论