2011-12-07 83 views
0

一個簡單的ajax調用,php回聲一些xml文本,我需要在JPayer中出現myAJAXVariable所在的位置。在變量中存儲ajax數據

我需要一些類似於PHP的回聲,它只是打印數據。

我只是想myAJAXVariable顯示來自getxml2.php

$(document).ready(function() { 



    var myAJAXVariable = $.get("http://www.freeenergymedia.com/getxml2.php", function(data){ 
return data; <!--here I am attempting to print the contents of getxml2.php as data--> 
}); 



    new jPlayerPlaylist({ 
     jPlayer: "#jquery_jplayer_1", 
     cssSelectorAncestor: "#jp_container_1" 
    }, myAJAXVariable, { 
     swfPath: "js", 
     supplied: "mp3, oga", 
     wmode: "window" 
    }); 

}); 

回答

2

數據由於AJAX(這是第一個A代表),你應該消耗的AJAX調用的結果的異步特性只成功回調裏面,否則數據將還沒有被初始化:

$(document).ready(function() { 
    $.get("http://www.freeenergymedia.com/getxml2.php", function(data) { 
     // Only here you should use the data variable as it is here and only here 
     // that it is assigned 

     new jPlayerPlaylist({ 
      jPlayer: "#jquery_jplayer_1", 
      cssSelectorAncestor: "#jp_container_1" 
     }, data, { 
      swfPath: "js", 
      supplied: "mp3, oga", 
      wmode: "window" 
     }); 
    }); 
}); 

,或者創建一個功能:

var initializejPlayer = function(data) { 
    new jPlayerPlaylist({ 
     jPlayer: "#jquery_jplayer_1", 
     cssSelectorAncestor: "#jp_container_1" 
    }, data, { 
     swfPath: "js", 
     supplied: "mp3, oga", 
     wmode: "window" 
    }); 
} 

然後觸發AJAX調用:

$(document).ready(function() { 
    $.get("http://www.freeenergymedia.com/getxml2.php", initializejPlayer); 
}); 
+0

@alex_borsody,在成功回調中,傳遞給匿名函數的'data'變量將包含執行'getxml2.php'的結果。這就是說,你應該知道相同的源策略限制,它阻止你發送AJAX請求到不同於發起域的域。因此,如果「www.freeenergymedia.com」不是您託管應用程序的域名,則無法向其發送AJAX請求。 –

1

你也可以考慮使用AJAX方法(這是比得到更多的配置,看這個線程Difference between $.ajax() and $.get() and $.load()形式的更多詳細信息)寫自己'的getData」功能。然後你可以使用你的函數來檢索代碼中的數據。

我個人使用此代碼從URL中檢索JSON數據,在我的Backbone.js的應用程序:

function getJSONData(myurl) 
var data; 
$.ajax({ 
    async: false, //thats the trick 
    url: myurl, 
    dataType: 'json', 
    success: function(response){ 
     data = response; 
     } 
    }); 
return data; 
} 

你可以使用不同的數據類型(XML,JSON,腳本或HTML),如果你需要(看這裏http://api.jquery.com/jQuery.ajax/) ,然後在你的情況,你可以在PlayerPlaylist對象使用它:

new jPlayerPlaylist({ 
    jPlayer: "#jquery_jplayer_1", 
    cssSelectorAncestor: "#jp_container_1" 
}, getJSONData("http://www.freeenergymedia.com/getxml2.php"), { 
    swfPath: "js", 
    supplied: "mp3, oga", 
    wmode: "window" 
}); 

希望這有助於。