0

This is probably pretty easy but I can't seem to find the answer anywhere.

I have a local javascript file with JSON data (data.js) that I would like to call from another js file (build.js) where I will name the array. How would you do this?

data.js

[
  {"name": "bob"},
  {"name": "sally"},
  {"name": "jane"}
]

build.js --> I've tried storing the data in a string and even that is not working...

var namesArray;

function build(){
    $.ajax({
        url: 'data.js',
        type: 'get',
        success: function(data) {
            namesArray = String(data); // this part doesn't work!!
        }
    });
}

$(document).ready(function(){
    build();
});

Ultimately what I want to achieve is to be able to call namesArray[0].name and be able to output "bob"... but I definitely do not want to name the array from within data.js. Help! Thanks!

p1xelarchitect
  • 289
  • 1
  • 6
  • 19

1 Answers1

4

You can specify to jQuery the type of the data and then use it directly.

function build(){
    $.ajax({
        url: 'data.js',
        type: 'get',
        dataType : 'json',
        success: function(data) {
            namesArray = data;
            console.log(namesArray[0].name); // bob
        }
    });
}
Magus
  • 14,796
  • 3
  • 36
  • 51
  • yep. this works. nice job! why is dataType needed to achieve this? – p1xelarchitect Jun 23 '14 at 12:58
  • 1
    This post answer your question: [stackoverflow.com/questions/2722750/ajax-datatype](http://stackoverflow.com/questions/2722750/ajax-datatype) – sprw Jun 23 '14 at 13:04