最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Passing variables through to AJAX - Stack Overflow

programmeradmin3浏览0评论

I have some variables that I would like to pass into an AJAX call:

e.g.

var moo = "cow noise";

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

However, moo es back undefined.

note, I've left url and data empty on purpose - they are populated in my code.

I have some variables that I would like to pass into an AJAX call:

e.g.

var moo = "cow noise";

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

However, moo es back undefined.

note, I've left url and data empty on purpose - they are populated in my code.

Share Improve this question asked Feb 18, 2011 at 13:54 Barrie ReaderBarrie Reader 10.7k11 gold badges76 silver badges141 bronze badges 3
  • I can't detect any problem. Please provide the actual code or a working bug. – Exelian Commented Feb 18, 2011 at 14:00
  • Please include the actual code. Your current example if perfectly fine. – Aron Rotteveel Commented Feb 18, 2011 at 14:05
  • What is the problem .I don't see any error ? – santosh singh Commented Feb 18, 2011 at 14:08
Add a ment  | 

3 Answers 3

Reset to default 8

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);
    }
  });
}
发布评论

评论列表(0)

  1. 暂无评论