javascript jquery和使用eval

时间:2011-03-30 08:59:24

标签: 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,但我得到“[”。 如果我使用eval函数

 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]);

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:0)

我认为jquery $ .getScript(' data.html',function(){alert(" success" + $(this).text())}可能更简单。我没有时间尝试,所以如果我走上正轨,改善这个答案,如果不是我现在很乐意学习......