我正在使用currenty jQuery插件讀取數據文件(data.html)JavaScript的jQuery和使用eval
data.html低於格式
[10,20,30,40,50]
我jQuery的數據請求和JavaScript返回值低於
function test(){
var result=$.ajax({
url:'data.html',
type:'get',
dataType:'text',
async:false,
cache:false
}).responseText
return result;};
var my=test();
alert(my[0])
我想在陣列格式即我希望我的[0]是值10以獲得這些值,而是我得到「[」。 如果我使用eval函數
my=eval(test());
我能得到10,但沒有任何其他更好的方式來存儲返回Ajax調用到一個數組,而不是字符串?
感謝
我嘗試了以下的答案,我有點納悶,在myarray的後續碼結果爲空(在螢火蟲),但我把異步:false,那麼它的工作原理。爲什麼我需要async:false將值存儲到數組中? (http://stackoverflow.com/questions/133310/how-can-i-get-jquery-to-perform-a-synchronous-rather-than-asynchronous-ajax-req)
jQuery.extend({getValues: function(url) {
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'json',
cache: false,
success: function(data) {result = data;}
});
return result;}});
myArray=$.getValues("data.html");
alert(myArray[1]);
+1對於解決方案-1對於推薦異步性,當它與問題無關時以及在更廣泛的用例中可能不需要/期望時。 – 2011-03-30 09:21:03
@tomalak我不能完全得到答案的工作,我需要存儲值進一步處理,因此它需要返回到主函數。我已經更新了我的問題,請你解釋我錯過了什麼? – Linus 2011-03-31 10:21:24