javascript jquery和使用eval
我目前正在使用jquery插件来读取数据文件(data.html)
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,但我得到“[”。 如果我使用evalfunction
my=eval(test());
我可以得到10,但有没有其他更好的方法将返回的ajax调用存储到数组而不是字符串?
谢谢
我尝试了下面的答案,我有点困惑,myArray中的跟随代码结果为null(在firebug中),但我把async: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]);
你不需要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();
我认为jquery $ .getScript(’data.html’,function(){alert(“success”+ $(this).text())}可能更简单。我没有时间尝试它,所以如果我是在正确的轨道上,改善这个答案,如果不是我现在很高兴学习…