Linus
Linus

Reputation: 845

javascript jquery and using eval

i am currenty using jquery plugin to read a data file (data.html)

data.html has below format

[10,20,30,40,50]

my jquery data request and the javascript to return values is below

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

i want to get these values in the array format i.e i want my[0] to be value 10, but instead i get "[". If i use eval function

 my=eval(test());

i can get 10, but is there any other better way to store the returned ajax calls into an array instead of string?

Thanks

i tried the below answer and i am bit puzzled, the follow code results in myArray is null (in firebug), but i put async:false then it works. why do i need async:false to store the values into array ? (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]);

Upvotes: 0

Views: 2931

Answers (2)

Jalkin
Jalkin

Reputation: 1132

I think jquery $.getScript('data.html',function(){alert("success"+$(this).text())} might be simpler. I have not had time to try it so if I'm on right track, improve this answer, if not I'm happy to learn now...

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038770

You don't need eval. Just indicate the proper dataType: 'json':

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

or even better do it asynchronously:

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

Upvotes: 5

Related Questions