如何使用jquery在ajax函数的回调函数中获取数据?

时间:2012-11-08 02:29:16

标签: jquery

从ajax调用获取返回数据的最佳选择是使用函数。在我的情况下,我调用函数returnData()但是如何在returnData()函数之外得到它?

           var testFile = $("#selection").val(),
           testData = getTestData(testFile); 

           function getTestData(testF) {
           $.getJSON("test.php", {
           fileTest: testF
           }, function (data) {
              $.each(data, function (index, value) {
                if (value != "") {} else {
                 testArray[index] = value;
               }
           });
       });
         returnData(testArray);
      } ​ 

2 个答案:

答案 0 :(得分:0)

在函数之外声明一个变量。

var testFile = $("#selection").val(),
    results = '', // We will store the results in this
    testData = getTestData(testFile); 

function returnData(valueReturned)
{
  results = valueReturned; // Store the results into that variable we created
  anotherFunction();
}

function getTestData(testF) {
    $.getJSON("test.php", {
        fileTest: testF
    }, function (data) {
        $.each(data, function (index, value) {
            if (value != "") {} else {
                testArray[index] = value;
            }
        });
    });
  returnData(testArray);
}​

function anotherFunction(){
  // We can access the contents of the results variable here :)
  console.log(results); 
}

答案 1 :(得分:0)

var result = null;

result = getTestData();

function getTestData(){
    return returnData(testArray);
}

alert(result);

顺便说一句,testArray首先定义在哪里?从您的代码看来,它已经在getTestData()之外定义。

此外,回调后面的代码可能会在AJAX函数返回之前执行:

var noodleIsCooked = false;

$.post("cook.php", {"Start cooking"}, function(){
    noodleIsCooked = true;
});

eatNoodle();

function eatNoodle(){
    if(!noodleIsCooked){
        alert("Yike I can't eat this!");
    }
}

以上代码几乎总是会触发警报。

但是,要吃熟面条,你需要将eatNoodle()放在回调中,如下所示:

$.post("cook.php", {"Start cooking"}, function(){
        noodleIsCooked = true;
        eatNoodle();
    });