0

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

2 Answers 2

5

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();
Sign up to request clarification or add additional context in comments.

2 Comments

+1 For the solution. -1 For recommending asynchronicity when it has nothing to do with the question and when it may not be required/desired in the wider use case.
@tomalak i could not quite get the answer working, i need to store the values for further processing hence it needs to be returned to the main function. i have updated my question can you please explain wht i have missed?
0

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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.