2012-03-12 2 views
0

에서 JSON 변수를 반환 할 수 없습니다 내가 기능을 가지고 :나는 JQuery와 아약스 기능

나는 함수에서 JSON 변수를 반환해야
function get_playlist(){  

     var result = jQuery.ajax({ 
      url: '<?php echo admin_url('admin-ajax.php'); ?>', 
      type: 'post', 
      dataType: 'json', 
      data: { 
       action: 'getrandommp3', 
       nonce:'<?php echo wp_create_nonce('randmp3'); ?>' 
      }, 
      success: function(response) { 
       console.log(response); // All OK! 
       window.response = response; 
       var customvar = response; 
       return response; 
      }    
     }); 
     console.log(window.response); // undefined 
     console.log(result.responseText); //undefined 
     console.log(customvar); //undefined 
     return window.response; // returning undefined 
    } 

. 내부에 success: function(response) { 응답 내용이 필요합니다. 하지만 ...

JQuery와 MP3 플레이어에 필요한이 코드 ... 내가 문제가 Jquery.ajax 외부

var playlist = get_playlist(); 
var myPlaylist = new jPlayerPlaylist(cssSelector, playlist, options); 
myPlaylist.shuffle(true, true); 

도움을 주셔서 감사합니다!

답변

2

이것은 AJAX가 (비동기 적으로) 작동하는 방식입니다. 응답 처리기가 반환되기 전에 이벤트 처리기 외부의 console.log 문이 실행되기 때문에 아직 아무 것도 window.response에 할당되지 않았습니다. success 이벤트 처리기 안에 AJAX 응답을 사용하는 코드를 넣으십시오.

또는 요청을 동기식으로 만들 수도 있지만 대개 응답을 반환 할 때까지 브라우저를 잠글 수 있기 때문에 원하는 것은 아닙니다. 내가 가진

function get_playlist(){  
    var result = jQuery.ajax({ 
     //Other AJAX options removed 
     success: function(response) { 
      var myPlaylist = new jPlayerPlaylist(cssSelector, response, options); 
      myPlaylist.shuffle(true, true); 
     }    
    }); 
} 
+0

: 나는 앞서 언급 한 바와 같이

업데이트 당신이 준비 이벤트 핸들러 내부에 AJAX 응답에 의존하는 모든 코드를 삽입 할 필요가

(의견과 편집 질문 참조) Jquery player와 json mp3의 목록을 반환해야합니다. 'var playlist = get_playlist(); \t \t \t var myPlaylist = new jPlayerPlaylist (cssSelector, playlist, options); \t \t \t myPlaylist.shuffle (true, true); ' –

+0

그리고 나서'success' 이벤트 핸들러 안에'jPlayer'를 만듭니다. 내 편집을 참조하십시오. –

+0

도움 주셔서 감사합니다) –