javascript jquery和使用eval

Lin*_*nus 0 javascript jquery eval

我目前正在使用jquery插件来读取数据文件(data.html)

data.html具有以下格式

[10,20,30,40,50]
Run Code Online (Sandbox Code Playgroud)

我的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])
Run Code Online (Sandbox Code Playgroud)

我想以数组格式获取这些值,即我希望我的[0]值为10,但我得到"[".如果我使用eval功能

 my=eval(test());
Run Code Online (Sandbox Code Playgroud)

我可以得到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]);
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 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]);
Run Code Online (Sandbox Code Playgroud)

甚至更好地异步做到:

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