2017-06-21 18 views
0

AJAXから取得したJSONオブジェクトの特定の値を取得しようとしています。AJAXから特定の値を取得すると、JSONオブジェクトが返される

console.log()を使用して、私はこれらを表示することができました。今、私は私が見つけることuserIdを使用して、データの別のリストでそれを一致させることができるように上記全体JSONオブジェクトを格納してみたい

0: Object 
    title: "First post" 
    body: "This is a post" 
    id: 1 
    userId: 27 
. 
. 
. 
100: //same format of data as object 0 

は、投稿したユーザー。問題は、私はそれをグローバル変数に格納することができないということです。ここに私のJScriptスニペットは次のとおりです。

var postJson; //global variable 

---somewhere in a function--- 
$.ajax({ 
     url: root + '/posts', 
     type: "GET", 
     dataType: "JSON", 
     success: function(response){ 
     postJson = response; 
     console.log(response);     
      } 
     }); 

私もpostJson = $.ajaxをやってみましたが、何も起こらなかったとpostJsonは未定義され続けています。

+0

ajax応答を受け取る前に、 'postJson'変数を使用しようとしている可能性があります。私はあなたが 'success'ハンドラの中でそれをコンソール化すれば、期待されるjsonオブジェクトを出力すると思います。 –

+0

グローバル変数に格納しようとすると、エラーメッセージは何ですか? – shole

+0

[非同期呼び出しからの応答を返すにはどうすればよいですか?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –

答えて

1

$アヤックスは非同期関数である、あなたはあなたが応答から変数を宣言する必要が関数を呼び出していない経由で直接行うことができますコールバックを使用するか、成功の機能に

var postJson; //global variable 

function doSomething(r){ 
    //r is here 
} 

---somewhere in a function--- 
$.ajax({ 
     url: root + '/posts', 
     type: "GET", 
     dataType: "JSON", 
     success: function(response){ 
      postJson = response; 

      //do something with postJson or call function doSomething(response)  
     } 
}); 
0
function doSomething(r){ 
    //r is here 
} 

---somewhere in a function--- 
$.ajax({ 
     url: root + '/posts', 
     type: "GET", 
     dataType: "JSON", 
     success: function(response){ 
     doSomething(response); 
      //do something with postJson or call function doSomething(response)  
     } 
}); 

をすべてのコードを実行する必要があります。それがあなたにも役立つことを願っています。

関連する問題