見出し画像

【jQuery】returnで取得した$.ajaxのレスポンス(戻り値)からJSONを取り出す

結論:PHPでJSONを取得してecho。JqueryからAjaxでphpファイルにアクセスした方が楽!

Ajaxは非同期通信のため普通にreturnしても戻り値はundefinedになってしまう(´・ω・`)

function sample(){
   $.ajax({
       type : "GET",
       url : "./hoge.json",
       dataType : "json",
       cache : false,
       success: function(data, status, xhr){
           //成功時の処理
           return 処理結果;
       },
       error: function(XMLHttpRequest, status, errorThrown){
           //失敗時の処理
           console.log("fail:" + XMLHttpRequest);
	    console.log("status:" + status);
           return 処理結果;
       });
}

var result = sample(); // undefined

成功時と失敗時の処理を外に出してあげることで関数の外で戻り値を使える

function sample(){
  return $.ajax({
       type : "GET",
       url : "./hoge.json",
       dataType : "json",
       cache : false,
  })
}

sample().done(function(data, status, xhr) {
  //成功時の処理

}).fail(function(XMLHttpRequest, status, errorThrown) {
  //失敗時の処理

});

var result = sample();

これでresultにJSONが代入できると思ったらjqXHRオブジェクトとかいう変なものが取得できた(´・ω・`)?

あ、でも一応、JSONも中に入ってるみたい。

jqXHRオブジェクト

こんな感じで書いたらうまく動いた

{
"message": "Hello World!"
};
function sample(){
  return $.ajax({
       type : "GET",
       url : "./hoge.json",
       dataType : "json",
       cache : false,
  })
.done(function(response) {
   console.log("ajax done.");
   console.log(response.message);
 }).fail(function(result) {
   失敗した時の処理
});
.done()メソッドで使っている関数内の変数responseには既に解析済みのJSONオブジェクトが入っています。これはresponse.messageのように扱うことができます。参照リンク

下の方法でJSONのみを取得することもできる

function sample(){
  return $.ajax({
       type : "GET",
       url : "./hoge.json",
       dataType : "json",
       cache : false,
  })
.done(function(data, textStatus, jqXHR) {
    console.log(data === jqXHR.responseJSON); //-> true
    console.log(data.message);
  })
.fail(function(jqXHR, textStatus, errorThrown){
 // エラーの場合処理
});

【追記】取得したjqXHRオブジェクトが部分的に読み込めない???

YouTubeAPIから動画の情報をJSONで読み込んだ時に発生

var video_info_json = sample();
console.log(video_info_json); //取得できる
console.log(video_info_json.respnseJSON); //取得できない???

responseJSONだけ受け取れない

非同期オプションをfalseにしたら解決

非同期

参考にしたホームページ

追記


この記事が気に入ったらサポートをしてみませんか?