1

取得したphpファイルからjson応答を取得するJquery ajax呼び出しを取得しました。json応答は素晴らしく、応答を正しくコンソールログに記録できますが、ajax結果の外に情報を保存できないようです。配列を更新しません。コードは次のようになり、結果を以下に投稿しました。

window.array={name: 'john',color:'red'};    

 console.log(array['name']);
 console.log(array['color']);

$.ajax({
    url : 'getJsons.php',
    type : 'POST',
    data : data,
    dataType : 'json',
    success : function (data) {

      array['name'] = data['name'];
      array['color'] = data['color'];
      console.log(array['name']);
      console.log(array['color']);
     }        
});

 console.log(array['name']);
 console.log(array['color']);

これにより、次のコンソールが表示されます。

 john
 red

 john
 red

 marry
 blue

だから私は最初にコンソールを正しく取得しますが、ajax 呼び出しの前に ajax 呼び出しの後にスクリプトをロードするようです。なぜですか? スクリプトが既にロードされた後にフェッチされているため、残りのコードで ajax の結果を使用することが不可能になるためです。残りの前にajaxを実行する方法はありますか?

4

4 に答える 4

1

何が起こっているかは、ajax 呼び出しが完了する前にクエリが実行された後のコードです。配列にデータが入力されました。心配はいりませんが、AJAX は非同期で実行されるため、ajax 呼び出しの後にのみ値が割り当てられます。

たとえば、ajax 呼び出しの後に 10 秒のタイムアウトを設定し (AJAX 呼び出しにかかった時間によって異なります)、配列値を呼び出した場合、値が入力されていることがわかります (AJAX が実行され、コールバック関数を適切に通過した場合)。 )。

したがって、コードでは、ここで段階的に何が起こるかを示します。

You display the values from the array which shows john red

You make the AJAX call, when this call has completed it will perform your success: function

The ajax call takes (lets say) 1 second to complete

Whilst your page is waiting for the call to complete and update the values it moves onto the next bit of code which displays the array, as the array hasn't been updated yet as success hasn't been called it still displays john red

1 seconds later the success function is called, assigns the new names to the array and prints them out.

于 2013-09-17T13:46:02.033 に答える
1

ajax 呼び出しは非同期です。つまり、ajax が実行されて返されるタイミングに関係なく、残りのコードが実行されます。コードが結果に依存する場合は、関数でラップし、ajax (成功関数) のコールバックから呼び出します。

于 2013-09-17T13:46:09.170 に答える
0

これが標準的なものかどうかはわかりませんが、うまくいきます:

var xmlURL = "Data/XML/"+GetURLParameter("xml");
var xmlInto = {};

$.get(xmlURL, function(xml) {
    $(xml).find("line").each(function(){
        xmlInto[line_number] = line_info;
    });             
}, 'xml');

console.log(xmlInto);
于 2013-09-17T14:01:43.983 に答える