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 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 に答える
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 に答える