2011-03-30 75 views
0

我正在使用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]); 

回答

5

你不不需要eval。只是指示正確dataType: 'json'

function test() { 
    return $.ajax({ 
     url: 'data.html', 
     type: 'get', 
     dataType: 'json', 
     async: false, 
     cache: false 
    }).responseText; 
} 
var my = test(); 
alert(my[0]); 

,甚至做得更好異步:

function test() { 
    $.ajax({ 
     url: 'data.html', 
     type: 'get', 
     dataType: 'json', 
     cache: false, 
     success: function(result) { 
      alert(result[0]); 
     } 
    }); 
} 
test(); 
+0

+1對於解決方案-1對於推薦異步性,當它與問題無關時以及在更廣泛的用例中可能不需要/期望時。 – 2011-03-30 09:21:03

+0

@tomalak我不能完全得到答案的工作,我需要存儲值進一步處理,因此它需要返回到主函數。我已經更新了我的問題,請你解釋我錯過了什麼? – Linus 2011-03-31 10:21:24

0

我認爲jQuery的$ .getScript( 'data.html',函數(){警報( 「成功」 + $(this).text())}可能會更簡單,我沒有時間去嘗試,所以如果我在正確的軌道上,改善這個答案,如果不是,我現在很高興現在去學習......