0

从 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);
      } ​ 
4

2 回答 2

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); 
}
于 2012-11-08T02:34:11.613 回答
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();
    });
于 2012-11-08T02:37:00.703 回答